package com.dminvoicemanager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.dminvoicemanager.backup.DM_Excel_Generator;
import com.dminvoicemanager.reports.DM_Customer_Last_Three_Visit;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class DM_Settings extends Activity {
	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String SALES_REP_ROUTEDET = "fRouteDet";
	private String BANK_DETAILS = "fBank";
	private String USER_EXPENSE = "fExpense";
	private String TOWN_DETAILS = "fTown";
	private String MERCH_DETAILS = "FMerch";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	private String SERVER_DETAILS = "serverinfo";
	private String SALES_DEALER = "fDealer";

	private String FTRGCAPUL = "FTrgCapUL";
	private String FTYPE = "fType";
	private String FSUBBRAND = "fSubBrand";
	private String FGROUP = "fGroup";
	private String FSKU = "fSku";
	private String FBRAND = "fbrand";
	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Sales Order
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";

	// Cash /Receipt header
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";

	// Adjustment
	private String TEMP_ADJUSTMENT_SUMMARY = "FAdjustmentSummary";
	private String ADJUST_ADDITION_HEADER = "FAdjHed";
	private String ADJUST_ADDITION_DETAILS = "FAdjDet";

	// Expense
	private String TEMP_DAYEXPENSE_SUMMARY = "FDayExpSummary";
	private String DAYEXPENSE_HEADER = "FDayExpHed";
	private String DAYEXPENSE_DETAILS = "FDayExpDet";

	private String RECEIPT_INVOICES = "FDDbNote";

	// None Productive Calls
	private String DAILY_NONE_PRDCALLS_HEAD = "fNonePrd";
	
	// None Productive Calls
	private String DAILY_NONE_PRDCALLS_HEADSO = "fNonePrdSO";

	private SQLiteDatabase mydb;
	// FDealer
	private CountDownTimer mCountDown;
	EditText etsettingsuser, etsettingsrepcode, etsettingslocationcode,
			etsettingsareacode, etsettingsroutecode, etsettingsdealcode,
			etsettingssdb, etsettingsrepprefix, etCurrentUrl;
	// Spinner element
	String currentServerDbName, currentSalesRepRoute, currentSalesRep,
			selectedServerDB, serverDbName = "0", repRoute = "0", selectToDate,
			selectFromDate,currentServerDB;
	AlertDialog SynchDetails = null;
	String TagId, fromLocCode, RecordIdFI;
	private Spinner serverDatbaeSpinner, serverFRouteSpinner, salesRepSpinner;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerDB;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerRoute;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerSalesRep;
	String CurrentUser, connectionURL, exportFileNamePrefix = "dbback";
	EditText etsettingsprintermac;
	private int mYear, mMonth, mDay, mHour, mMinute;
	int stYear = 2000;
	int arrayLength = 0;
	int NetFail = 0;
	int DateTag = 0;
	int toDayTag = 0;
	Date date;
	AlertDialog InvoiceHeaderAlert = null;
	Button editCurrentServerURL, synchServerDb, processbackup, generatePDF,
			generateBackup, btndmreportfromdate, btndmreporttodate,
			rescheduleUploading, backupDatabase,viewGpsRecords;
	// flag for Internet connection status
	Boolean isInternetPresent = false;
	// Connection detector class
	DM_ConnectionDetector cd;
	private XmlBuilder xmlBuilder;
	static final int DATE_DIALOG_ID_FROM = 0;
	static final int DATE_DIALOG_ID_TO = 1;
	final private static int DIALOG_SYNC_SUCCESS = 2;
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	LinearLayout dminvoiceuploadreschedule;
	Context ctx = DM_Settings.this;

	public void DataXmlExporter(SQLiteDatabase mydb) {
		this.mydb = mydb;
	}

	public void SyncCompleteAccept(View view) {
		saveServerDB();
		Intent myIntent = new Intent(view.getContext(), DM_Settings.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "RELOAD");
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	private void saveServerDB() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectServerInfo = null;
		try {
			selectServerInfo = mydb.query(SERVER_DETAILS, null,
					"server_id = '1'", null, null, null, null);
		} catch (Exception e) {
		}
		
		if (selectServerInfo != null) {
			if (selectServerInfo.getCount() > 0) {
				while (selectServerInfo.moveToNext()) {
					ContentValues userPrinter = new ContentValues();
					userPrinter.put("serverdbname", etsettingssdb.getText().toString());
					mydb.update(SERVER_DETAILS, userPrinter, "server_id ='1'", null);
				}
			}
		}
		selectServerInfo.close();
		mydb.close();
	}

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		// myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void btnExitSettings(View view) {
		if (etsettingsuser.length() == 0
				|| etsettingslocationcode.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Settings.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT SALES REP");
			// Setting Dialog Message
			alertDialog.setMessage("Select User From The List..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);

		} else if (etsettingsroutecode.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Settings.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT SALES REP ROUTE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Sales Rep Route From The List..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
		} else {

			if (TagId.equals("SUPPER")) {
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceMainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
				return;
			} else {
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceMainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				// myIntent.putExtra("TAGID", "SALES");
				startActivityForResult(myIntent, 0);
				finish();
				return;
			}
		}
	}

	public void btnSaveUserSettings(View view) {
		Log.v(TAG, "btnSaveUserSettings");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUdateUserPrinterSetting = null;
		try {
			curUdateUserPrinterSetting = mydb.query(USER_SETTINGS, null,
					"username = '" + CurrentUser + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUdateUserPrinterSetting != null) {
			if (curUdateUserPrinterSetting.getCount() > 0) {
				while (curUdateUserPrinterSetting.moveToNext()) {
					Log.v(TAG, "while");
					if (etsettingssdb.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SERVER DB");
						// Setting Dialog Message
						alertDialog.setMessage("Select User's Server Databse From The List..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
					}
					else if (etsettingsuser.length() == 0
							|| etsettingslocationcode.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SALES REP");
						// Setting Dialog Message
						alertDialog.setMessage("Select User From The List..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);

					} else if (etsettingsroutecode.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SALES REP ROUTE");
						// Setting Dialog Message
						alertDialog
								.setMessage("Select Sales Rep Route From The List..");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
					} else {
						Log.v(TAG, "Exception 3");
						String CurrentUserId = curUdateUserPrinterSetting
								.getString(0);
						CurrentUser = curUdateUserPrinterSetting.getString(1);
						ContentValues userPrinter = new ContentValues();
						userPrinter.put("username", etsettingsrepcode.getText()
								.toString());
						userPrinter.put("lrepprefix", etsettingsrepprefix
								.getText().toString());
						userPrinter.put("lreploccode", etsettingslocationcode
								.getText().toString());
						userPrinter.put("locationCode", etsettingslocationcode
								.getText().toString());
						userPrinter.put("serverDbName", etsettingssdb.getText()
								.toString());
						userPrinter.put("printerMac", etsettingsprintermac
								.getText().toString());
						userPrinter.put("repareacode", etsettingsareacode
								.getText().toString());
						userPrinter.put("repdealcode", etsettingsdealcode
								.getText().toString());
						userPrinter.put("reproutecode", etsettingsroutecode
								.getText().toString());
						mydb.update(USER_SETTINGS, userPrinter, "_id ='1'",
								null);

						alertUserUpdate();
					}
				}
			} else {
				Log.v(TAG, "Exception 2");
				try {
					ContentValues userPrinter = new ContentValues();

					userPrinter.put("username", etsettingsrepcode.getText()
							.toString());
					userPrinter.put("lrepprefix", etsettingsrepprefix.getText()
							.toString());
					userPrinter.put("lreploccode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("currentStOrdNo", "0");
					userPrinter.put("locationCode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("receiptCode", "0");
					userPrinter.put("serverDbName", etsettingssdb.getText()
							.toString());
					userPrinter.put("printerMac", etsettingsprintermac
							.getText().toString());
					userPrinter.put("repareacode", etsettingsareacode.getText()
							.toString());
					userPrinter.put("repdealcode", etsettingsdealcode.getText()
							.toString());
					userPrinter.put("reproutecode", etsettingsroutecode
							.getText().toString());
					mydb.insert(USER_SETTINGS, null, userPrinter);
					alertUserUpdate();

				} catch (Exception e) {
					Log.v(TAG, "Exception 1");
					// Toast.makeText(this, e.toString(),
					// Toast.LENGTH_LONG).show();
				}
			}
		} else {
			ContentValues userPrinter = new ContentValues();

			userPrinter.put("username", etsettingsrepcode.getText().toString());
			userPrinter.put("lrepprefix", etsettingsrepprefix.getText()
					.toString());
			userPrinter.put("lreploccode", etsettingslocationcode.getText()
					.toString());
			userPrinter.put("currentStOrdNo", "0");
			userPrinter.put("locationCode", etsettingslocationcode.getText()
					.toString());
			userPrinter.put("receiptCode", "0");
			userPrinter.put("serverDbName", etsettingssdb.getText().toString());
			userPrinter.put("printerMac", etsettingsprintermac.getText()
					.toString());
			userPrinter.put("repareacode", etsettingsareacode.getText()
					.toString());
			userPrinter.put("repdealcode", etsettingsdealcode.getText()
					.toString());
			userPrinter.put("reproutecode", etsettingsroutecode.getText()
					.toString());
			mydb.insert(USER_SETTINGS, null, userPrinter);

			alertUserUpdate();
		}
	}

	private void alertUserUpdate() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_Settings.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("UPDATE SETINGS");
		// Setting Dialog Message
		alertDialog.setMessage("User Settings Updated Successfully..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
				exitFromSettings();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
	}

	protected void exitFromSettings() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(this, DM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		// myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
	}

	// Get Current date and time for Alert Dialog
	public DM_Settings() {
		// Assign current Date and Time Values to Variables
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_settings);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		// Spinner element
		serverDatbaeSpinner = (Spinner) findViewById(R.id.spinnerServerDB);
		serverFRouteSpinner = (Spinner) findViewById(R.id.salesrepRouteList);
		salesRepSpinner = (Spinner) findViewById(R.id.salesrepList);

		etsettingsuser = (EditText) findViewById(R.id.etsettingsuser);
		etsettingsrepcode = (EditText) findViewById(R.id.etsettingsrepcode);
		etsettingsrepprefix = (EditText) findViewById(R.id.etsettingsrepprefix);
		etsettingslocationcode = (EditText) findViewById(R.id.etsettingslocationcode);
		etsettingsareacode = (EditText) findViewById(R.id.etsettingsareacode);
		etsettingsroutecode = (EditText) findViewById(R.id.etsettingsroutecode);
		etsettingsdealcode = (EditText) findViewById(R.id.etsettingsdealcode);
		etsettingssdb = (EditText) findViewById(R.id.etsettingssdb);
		etsettingsprintermac = (EditText) findViewById(R.id.etsettingsprintermac);
		etCurrentUrl = (EditText) findViewById(R.id.printcurrenturl);
		editCurrentServerURL = (Button) findViewById(R.id.editcurrentserverURL);
		processbackup = (Button) findViewById(R.id.processbackup);
		generatePDF = (Button) findViewById(R.id.generatePDF);
		generateBackup = (Button) findViewById(R.id.generateBackup);
		viewGpsRecords = (Button) findViewById(R.id.viewGpsRecords);
		
		btndmreportfromdate = (Button) findViewById(R.id.btndmreportfromdate);
		btndmreporttodate = (Button) findViewById(R.id.btndmreporttodate);
		rescheduleUploading = (Button) findViewById(R.id.rescheduleUploading);
		backupDatabase = (Button) findViewById(R.id.backupDatabase);
		dminvoiceuploadreschedule = (LinearLayout) findViewById(R.id.dminvoiceuploadreschedule);

		backupDatabase.setOnClickListener(new OnClickListener() {

			public void onClick(View view)

			{

				try

				{

					new ExportDatabaseFileTask().execute("");

				}

				catch (Exception ex)

				{

					Log.e("Error in MainActivity", ex.toString());

				}

			}

		});

		cd = new DM_ConnectionDetector(getApplicationContext());
		getConnectionUrl();
		displayCurrentSettings();
		loadServerDataBase();
		loadToMainStoreRouteSpinner();
		loadToMainStoreSalesRepSpinner();

		viewGpsRecords.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Discover_GPS.class);
			/*	myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);*/
				startActivityForResult(myIntent, 0);
			}
		});
		
		editCurrentServerURL.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Properties.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		generateBackup.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Excel_Generator.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});

		processbackup.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// exportDB();
				try {
					export(DBNAME, exportFileNamePrefix);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		generatePDF.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

			}
		});

		rescheduleUploading.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resheduleProcess();
			}
		});

		/*
		 * backupDatabase.setOnClickListener(new View.OnClickListener() { public
		 * void onClick(View view) { //datbaseBackupProcess();
		 * 
		 * } });
		 */

		synchServerDb = (Button) findViewById(R.id.synchServerDb);
		synchServerDb.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					logYearsList();
					logMonthList();
					if (serverDbName.equals("0")) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SERVER DB");
						// Setting Dialog Message
						alertDialog
								.setMessage("Select Server Database From List...");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						UpdateUserSettings();
						synchMasterTableData();
					}

				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_Settings.this, "No Internet Connection",
							"You don't have internet connection.", false);
				}

			}

		});

		if (TagId.equals("SALES")) {
			serverDatbaeSpinner.setEnabled(false);
			salesRepSpinner.setEnabled(false);
			synchServerDb.setEnabled(false);
			editCurrentServerURL.setEnabled(false);
		} else if (TagId.equals("SUPPER")) {
			dminvoiceuploadreschedule.setEnabled(false);
		}

		serverDatbaeSpinner.setAdapter(m_adapterForSpinnerDB);
		serverDatbaeSpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						currentServerDbName = serverDatbaeSpinner
								.getSelectedItem().toString();
						if (!(currentServerDbName.equals("SELECT SERVER DB"))) {

							SQLiteDatabase mydb;
							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(SERVER_DB_LIST,
										null, "sdbname='" + currentServerDbName
												+ "'", null, null, null, null,
										null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {

									while (getfromloccur.moveToNext()) {
										fromLocCode = getfromloccur
												.getString(0);
										serverDbName = getfromloccur
												.getString(1);
										etsettingssdb
												.setText(currentServerDbName);
									}
								}
								getfromloccur.close();
							}

						} else {
							serverDbName = "0";
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		// ===============Load Route Details=========================
		serverFRouteSpinner.setAdapter(m_adapterForSpinnerRoute);
		serverFRouteSpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						currentSalesRepRoute = serverFRouteSpinner
								.getSelectedItem().toString();
						if (!(currentSalesRepRoute
								.equals("SELECT SALES REP ROUTE"))) {

							SQLiteDatabase mydb;
							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(SALES_REP_ROUTE,
										null, "RouteName='"
												+ currentSalesRepRoute + "'",
										null, null, null, null, null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {

									while (getfromloccur.moveToNext()) {
										fromLocCode = getfromloccur
												.getString(2);
										repRoute = getfromloccur.getString(3);
										etsettingsroutecode
												.setText(fromLocCode);
									}
								}
								getfromloccur.close();
							}

						} else {
							repRoute = "0";
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		// ===============Load SalesRep Details=========================
		salesRepSpinner.setAdapter(m_adapterForSpinnerSalesRep);
		salesRepSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				currentSalesRep = salesRepSpinner.getSelectedItem().toString();
				if (!(currentSalesRep.equals("SELECT SALESREP"))) {

					SQLiteDatabase mydb;
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);

					Cursor getSalesRepDet = null;
					try {
						String querySalRep = "SELECT R.AreaCode,R.DealCode,R.RepCode,R.RepPrefix,L.LocCode,R.RepName FROM fSalRep R,fLocation L Where R.RepCode = L.RepCode AND R.RepCode ='"
								+ currentSalesRep + "' AND L.LoctCode ='LT3'";
						getSalesRepDet = mydb.rawQuery(querySalRep, null);

					} catch (Exception e) {

					}
					if (getSalesRepDet != null) {
						if (getSalesRepDet.getCount() > 0) {

							while (getSalesRepDet.moveToNext()) {
								String strAreaCode = getSalesRepDet
										.getString(0);
								String strDealCode = getSalesRepDet
										.getString(1);
								String strRepCode = getSalesRepDet.getString(2);
								String strRepPrefix = getSalesRepDet
										.getString(3);
								String strLocCode = getSalesRepDet.getString(4);
								String strRepName = getSalesRepDet.getString(5);

								etsettingsuser.setText(strRepName);
								etsettingsrepcode.setText(strRepCode);
								etsettingsrepprefix.setText(strRepPrefix);
								etsettingslocationcode.setText(strLocCode);
								etsettingsareacode.setText(strAreaCode);
								etsettingsdealcode.setText(strDealCode);
							}
						} else {
							etsettingsuser.setText("");
							etsettingsrepprefix.setText("");
							etsettingsrepcode.setText("");
							etsettingslocationcode.setText("");
							etsettingsareacode.setText("");
							etsettingsdealcode.setText("");
							etsettingsroutecode.setText("");
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_Settings.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("UNAUTHORIZED SALES REP");
							// Setting Dialog Message
							alertDialog
									.setMessage("Selected Sales Rep Not Authorized.Select Another Sales Rep...");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();
											return;
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
						getSalesRepDet.close();
					} else {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("UNAUTHORIZED SALES REP");
						// Setting Dialog Message
						alertDialog
								.setMessage("Selected Sales Rep Not Authorized.Select Another Sales Rep...");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
										return;
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}

				} else {
					repRoute = "0";
				}

			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		// Set ClickListener on btnSelectDate
		btndmreportfromdate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				DateTag = 30;
				showDialog(DATE_DIALOG_ID_FROM);
			}
		});

		// Set ClickListener on btnSelectDate
		btndmreporttodate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				DateTag = 40;
				showDialog(DATE_DIALOG_ID_TO);
			}
		});
	}

	protected void datbaseBackupProcess() {
		Log.e("RES DJ2:", "datbaseBackupProcess");
		// TODO Auto-generated method stub
	}

	class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean>

	{

		private final ProgressDialog dialog = new ProgressDialog(ctx);

		// can use UI thread here

		@Override
		protected void onPreExecute()

		{

			this.dialog.setMessage("Exporting database...");

			this.dialog.show();

		}

		// automatically done on worker thread (separate from UI thread)

		protected Boolean doInBackground(final String... args)

		{

			File dbFile = new File(Environment.getDataDirectory() +

			"/data/com.dminvoicemanager/databases/dminvoicemanager.db");

			File exportDir = new File(
					Environment.getExternalStorageDirectory(), "");

			if (!exportDir.exists())

			{

				exportDir.mkdirs();

			}

			File file = new File(exportDir, dbFile.getName());

			try

			{

				file.createNewFile();

				this.copyFile(dbFile, file);

				return true;

			}

			catch (IOException e)

			{

				Log.e("mypck", e.getMessage(), e);

				return false;

			}

		}

		// can use UI thread here

		@Override
		protected void onPostExecute(final Boolean success)

		{

			if (this.dialog.isShowing())

			{

				this.dialog.dismiss();

			}

			if (success)

			{

				/*Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT)
						.show();*/
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Settings.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("BACKUP SUCCESS");
				// Setting Dialog Message
				alertDialog.setMessage("Database Export successfully...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
			}

			else

			{
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Settings.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("BACKUP FAIL");
				// Setting Dialog Message
				alertDialog.setMessage("Database Export Fail...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				//Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();

			}

		}

		void copyFile(File src, File dst) throws IOException

		{

			FileChannel inChannel = new FileInputStream(src).getChannel();

			FileChannel outChannel = new FileOutputStream(dst).getChannel();

			try

			{

				inChannel.transferTo(0, inChannel.size(), outChannel);

			}

			finally

			{

				if (inChannel != null)

					inChannel.close();

				if (outChannel != null)

					outChannel.close();

			}

		}

	}

	// Reschedule Uploading Sync State
	protected void resheduleProcess() {
		// TODO Auto-generated method stub
		if (btndmreportfromdate.length() == 0
				|| btndmreporttodate.length() == 0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Settings.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT DATE RANGE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Resehedule Date Range First...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			selectFromDate = btndmreportfromdate.getText().toString();
			selectToDate = btndmreporttodate.getText().toString();
			try {
				date = originalFormat.parse(selectFromDate.replaceAll(
						"[-+/.^:,]", " "));
				selectFromDate = targetFormat.format(date);

				date = originalFormat.parse(selectToDate.replaceAll(
						"[-+/.^:,]", " "));
				selectToDate = targetFormat.format(date);
			} catch (ParseException ex) {

			}

			if (selectFromDate.equals(selectToDate)) {
				toDayTag = 33;
				Log.e("RES DJ2:", "Date CHECK :" + toDayTag);
			}
			SQLiteDatabase mydb;
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

			// *****FinvHed Sync State Changing******
			Cursor curfInvHed = null, curfInvdet = null;
			String fInvHedQuery = null, fInvdetQuery = null;

			try {
				if (toDayTag == 33) {
					fInvHedQuery = "SELECT invhedSync,AddDateInvHead from FinvHed Where AddDateInvHead >= '"
							+ selectFromDate.trim() + "'";

					fInvdetQuery = "SELECT invdetSync,invsysdate from FinvDet Where invsysdate >= '"
							+ selectFromDate.trim() + "'";
				} else {
					fInvHedQuery = "SELECT invhedSync,AddDateInvHead from FinvHed Where AddDateInvHead >= '"
							+ selectFromDate.trim()
							+ "' AND AddDateInvHead <= '"
							+ selectToDate.trim()
							+ "'";

					fInvdetQuery = "SELECT invdetSync,invsysdate from FinvDet Where invsysdate >= '"
							+ selectFromDate.trim()
							+ "' AND invsysdate <= '"
							+ selectToDate.trim() + "'";
				}
			} catch (Exception e) {

			}
			curfInvHed = mydb.rawQuery(fInvHedQuery, null);
			curfInvdet = mydb.rawQuery(fInvdetQuery, null);
			Log.e("RES DJ2:", "Date CHECK  HED :" + curfInvHed.getCount());
			Log.e("RES DJ2:", "Date CHECK  DET :" + curfInvdet.getCount());
			if (curfInvHed != null) {
				if (curfInvHed.getCount() > 0) {
					while (curfInvHed.moveToNext()) {
						ContentValues recordUpdateFinvHed = new ContentValues();
						recordUpdateFinvHed.put("invhedSync", "0");
						mydb.update(INV_HEADER, recordUpdateFinvHed,
								"invhedSync = '1'", null);
					}
				}
			}

			if (curfInvdet != null) {
				if (curfInvdet.getCount() > 0) {
					while (curfInvdet.moveToNext()) {
						ContentValues recordUpdateFinvHed = new ContentValues();
						recordUpdateFinvHed.put("invdetSync", "0");
						mydb.update(INV_DETAILS, recordUpdateFinvHed,
								"invdetSync = '1'", null);
					}
				}
			}

			// *****FordDet Sync State Changing******
			Cursor curfOrdHed = null, curfOrddet = null;
			String fOrdHedQuery = null, fOrddetQuery = null;

			try {
				if (toDayTag == 33) {
					fOrdHedQuery = "SELECT stordhedSync,ohAddDate from FOrdHed Where ohAddDate >= '"
							+ selectFromDate.trim() + "'";

					fOrddetQuery = "SELECT odAddDate ,storddetSync from FOrddet Where odAddDate >= '"
							+ selectFromDate.trim() + "'";
				} else {
					fOrdHedQuery = "SELECT stordhedSync,ohAddDate from FOrdHed Where ohAddDate >= '"
							+ selectFromDate.trim()
							+ "' AND ohAddDate <= '"
							+ selectToDate.trim() + "'";

					fOrddetQuery = "SELECT odAddDate ,storddetSync from FOrddet Where odAddDate >= '"
							+ selectFromDate.trim()
							+ "' AND odAddDate <= '"
							+ selectToDate.trim() + "'";
				}
			} catch (Exception e) {

			}

			curfOrdHed = mydb.rawQuery(fOrdHedQuery, null);
			curfOrddet = mydb.rawQuery(fOrddetQuery, null);
			if (curfOrdHed != null) {
				if (curfOrdHed.getCount() > 0) {
					while (curfOrdHed.moveToNext()) {
						ContentValues recordUpdateFOrdHed = new ContentValues();
						recordUpdateFOrdHed.put("stordhedSync", "0");
						mydb.update(STOCK_ORDER_HEAD, recordUpdateFOrdHed,
								"stordhedSync = '1'", null);
					}
				}
			}

			if (curfOrddet != null) {
				if (curfOrddet.getCount() > 0) {
					while (curfOrddet.moveToNext()) {
						ContentValues recordUpdateFOrdDet = new ContentValues();
						recordUpdateFOrdDet.put("storddetSync", "0");
						mydb.update(STOCK_ORDER_DETAIL, recordUpdateFOrdDet,
								"storddetSync = '1'", null);
					}
				}
			}

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Settings.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Sync Reschedule Success");
			// Setting Dialog Message
			alertDialog
					.setMessage("Sync Reschedule Success.Sync Sate Changed..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					btndmreportfromdate.setText("");
					btndmreporttodate.setText("");
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// Select Dates

	public void export(String dbName, String exportFileNamePrefix)
			throws IOException {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		this.xmlBuilder = new XmlBuilder();
		this.xmlBuilder.start(dbName);

		// get the tables
		String sql = "select * from sqlite_master";
		Cursor c = this.mydb.rawQuery(sql, new String[0]);

		if (c.moveToFirst()) {
			do {
				String tableName = c.getString(c.getColumnIndex("name"));

				// skip metadata, sequence, and uidx (unique indexes)
				if (!tableName.equals("android_metadata")
						&& !tableName.equals("sqlite_sequence")
						&& !tableName.startsWith("uidx")) {
					this.exportTable(tableName);
				}
			} while (c.moveToNext());
		}
		String xmlString = this.xmlBuilder.end();
		this.writeToFile(xmlString, exportFileNamePrefix + ".xml");
	}

	private void exportTable(final String tableName) throws IOException {
		this.xmlBuilder.openTable(tableName);
		String sql = "select * from " + tableName;
		Cursor c = this.mydb.rawQuery(sql, new String[0]);
		if (c.moveToFirst()) {
			int cols = c.getColumnCount();
			do {
				this.xmlBuilder.openRow();
				for (int i = 0; i < cols; i++) {
					this.xmlBuilder.addColumn(c.getColumnName(i),
							c.getString(i));
				}
				this.xmlBuilder.closeRow();
			} while (c.moveToNext());
		}
		c.close();
		this.xmlBuilder.closeTable();
	}

	private void writeToFile(String xmlString, String exportFileName)
			throws IOException {
		File dir = new File(Environment.getExternalStorageDirectory(), DBNAME);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, exportFileName);
		file.createNewFile();

		ByteBuffer buff = ByteBuffer.wrap(xmlString.getBytes());
		FileChannel channel = new FileOutputStream(file).getChannel();
		try {
			channel.write(buff);
		} finally {
			if (channel != null)
				channel.close();
		}
	}

	protected void exportDB() {
		// TODO Auto-generated method stub

		/*
		 * try { File sd = Environment.getExternalStorageDirectory(); File data
		 * = Environment.getDataDirectory();
		 * 
		 * if (sd.canWrite()) { String currentDBPath =
		 * "data/data/com.dminvoicemanager/databases/dminvoicemanager.db";
		 * String backupDBPath = "data/data/com.dminvoicemanager/"; File
		 * currentDB = new File(data, currentDBPath); File backupDB = new
		 * File(sd, backupDBPath);
		 * 
		 * FileChannel src = new FileInputStream(currentDB).getChannel();
		 * FileChannel dst = new FileOutputStream(backupDB).getChannel();
		 * dst.transferFrom(src, 0, src.size()); src.close(); dst.close();
		 * Toast.makeText(getApplicationContext(), "Backup Successful!",
		 * Toast.LENGTH_SHORT).show();
		 * 
		 * } } catch (Exception e) {
		 * 
		 * Toast.makeText(getApplicationContext(), "Backup Failed!",
		 * Toast.LENGTH_SHORT) .show();
		 * 
		 * }
		 */
	}

	// Alert View Validating Network Connection
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				new DownloadAdministrative().execute();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					currentServerDB = getserverurl.getString(3);
					etsettingssdb.setText(currentServerDB);
					etCurrentUrl.setText(connectionURL);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}
		getserverurl.close();
		mydb.close();
	}

	private void loadToMainStoreSalesRepSpinner() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerSalesRep = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerSalesRep
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curRoute = null;
		try {
			curRoute = mydb.query(INV_SAL_REP, null, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (curRoute != null) {
			if (curRoute.getCount() > 0) {
				m_adapterForSpinnerSalesRep.add("SELECT SALESREP");
				while (curRoute.moveToNext()) {
					m_adapterForSpinnerSalesRep.add(curRoute.getString(5));
				}
			}
			curRoute.close();
		}
		mydb.close();

	}

	private void logYearsList() {
		// TODO Auto-generated method stub
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			for (int i = stYear; i <= 2033; i++) {
				ContentValues newYearRaw = new ContentValues();
				String strYear = Integer.toString(stYear);
				newYearRaw.put("yearname", strYear);
				mydb.insert(YEARS_LIST, null, newYearRaw);
				stYear = stYear + 1;
			}
		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		mydb.close();
	}

	private void logMonthList() {
		// TODO Auto-generated method stub
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('1','January')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('2','February')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('3','March')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('4','April')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('5','May')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('6','June')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('7','July')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('8','August')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('9','September')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('10','October')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('11','November')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('12','December')");
			mydb.close();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	private void loadToMainStoreRouteSpinner() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerRoute = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerRoute
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curRoute = null;
		try {
			curRoute = mydb.query(SALES_REP_ROUTE, null, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curRoute != null) {
			if (curRoute.getCount() > 0) {
				m_adapterForSpinnerRoute.add("SELECT SALES REP ROUTE");
				while (curRoute.moveToNext()) {
					m_adapterForSpinnerRoute.add(curRoute.getString(3));
				}
			}
			curRoute.close();
		}
		mydb.close();

	}

	private void loadServerDataBase() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerDB = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerDB
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curServerDB = null;
		try {
			curServerDB = mydb.query(SERVER_DB_LIST, null, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curServerDB != null) {
			if (curServerDB.getCount() > 0) {
				m_adapterForSpinnerDB.add("SELECT SERVER DB");
				while (curServerDB.moveToNext()) {
					m_adapterForSpinnerDB.add(curServerDB.getString(1));
				}
			}
			curServerDB.close();
		}
		mydb.close();
	}

	// Synch Master table data for the application
	protected void synchMasterTableData() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {

			mydb.execSQL("DROP TABLE IF EXISTS FCompanySetting");
			mydb.execSQL("DROP TABLE IF EXISTS FCompanyBranch");
			mydb.execSQL("DROP TABLE IF EXISTS fControl");
			mydb.execSQL("DROP TABLE IF EXISTS fSalRep");
			mydb.execSQL("DROP TABLE IF EXISTS fArea");
			mydb.execSQL("DROP TABLE IF EXISTS fLocation");
			mydb.execSQL("DROP TABLE IF EXISTS fDebtor");
			mydb.execSQL("DROP TABLE IF EXISTS fItemLoc");
			mydb.execSQL("DROP TABLE IF EXISTS fReason");
			mydb.execSQL("DROP TABLE IF EXISTS fItems");
			mydb.execSQL("DROP TABLE IF EXISTS fItemPri");
			mydb.execSQL("DROP TABLE IF EXISTS fBank");
			mydb.execSQL("DROP TABLE IF EXISTS fRoute");
			mydb.execSQL("DROP TABLE IF EXISTS fRouteDet");
			mydb.execSQL("DROP TABLE IF EXISTS fExpense");
			mydb.execSQL("DROP TABLE IF EXISTS fTown");
			mydb.execSQL("DROP TABLE IF EXISTS FMerch");
			mydb.execSQL("DROP TABLE IF EXISTS FDDbNote");
			mydb.execSQL("DROP TABLE IF EXISTS fNonePrd");
			mydb.execSQL("DROP TABLE IF EXISTS fNonePrdSO");
			
			mydb.execSQL("create table if not exists "
					+ SALES_DEALER
					+ "(_id integer primary key autoincrement,DealCode text not null,DealName text not null,DealAdd1 text not null,DealAdd2 text not null,DealAdd3 text not null,DealTele text not null,DealMob text not null,DealEMail text not null,Status text not null,Distance text not null,DealGdCode text not null,CusTypCode text not null,AddUser text not null,AddDate text not null,AddMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ YEARS_LIST
					+ "(year_id integer primary key autoincrement,yearname text not null);");

			mydb.execSQL("create table if not exists "
					+ MONTH_LIST
					+ "(month_id integer primary key autoincrement,monthindex text not null,monthname text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DETAILS
					+ "(server_id integer primary key autoincrement,serverurl text not null,portval text not null,serverdbname text not null,activeproperty text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DB_LIST
					+ "(sdb_id integer primary key autoincrement,sdbname text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_SETTINGS
					+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null,locationCode text not null,receiptCode text not null,serverDbName text not null,printerMac text not null,repareacode text not null,repdealcode text not null,reproutecode text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_AREA
					+ "(farea_id integer primary key autoincrement,AreaCode text not null,AreaName text not null,RegCode text not null,DealCode text not null,AddUser text not null,AddDatefarea text not null,AddMach text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_REP_INVOICESUMERY
					+ "(remprepinv_id integer primary key autoincrement,repusername text not null,repprefix text not null,tempRepInvNoCode text not null,tempRepInvSerial text not null,invoiceComplete text not null,activeInvoice text not null,activeInvoiceValue text not null,activeInvItemDiscount text not null,activeInvCusDiscount text not null,activeInvCusDiscountValue text not null,InvoiceCustomerCode text not null,InvoiceCustomerName text not null,InvoiceSynchState text not null,recordDate text not null,recordSynchDate text not null,invlateststate text not null,activeInvoiceReturnValue text not null,activeInvoiceRemarks text not null,invoiceNoOfItems text not null,invoiceRef text not null,invoiceRefStl text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOCATION
					+ "(flocation_id integer primary key autoincrement,AddMach text not null,AddUser text not null,Address1 text not null,Address2 text not null,Address3 text not null,Contact text not null,EMail text not null,FaxNo text not null,LocCode text not null,LocName text not null,LoctCode text not null,RecordId text not null,RepCode text not null,TeleNo text not null,LocAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEMS
					+ "(_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,MapCode text not null,ItemName text not null,VenPcode text not null,GroupCode text not null,TypeCode text not null,TaxComCode text not null,UnitCode text not null,SkuSizCode text not null,ItemStatus text not null,ReOrderLvl text not null,ReOrderQty text not null,AvgPrice text not null,PurAcc text not null,PurRetAcc text not null,SVATAcc text not null,ExportAcc text not null,IndrExAcc text not null,SalAcc text not null,SalRetAcc text not null,DisAcc text not null,ClsStkAcc text not null,StkInAcc text not null,PrilCode text not null,BrandCode text not null,SBrandCode text not null,NOUCase text not null,OrdSeq text not null,AddUser text not null,AddDatefitem text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,MustSale  text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_PRICE
					+ "(fitempri_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,PrilCode text not null,PriRDate text not null,Price text not null,AddUser text not null,AddDateIP text not null,AddMach text not null,Txnuser text not null,TxnDate text not null,TxnMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOC_DETAILS
					+ "(flocdet_id integer primary key autoincrement,LocCode text not null,ItemCode text not null,QOH text not null,RecordId text not null,timestamp_column text not null,syncRec text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_DEBTOR
					+ "(_id integer primary key autoincrement,DebCode text not null,DebName text not null,DebAdd1 text not null,DebAdd2 text not null,DebAdd3 text not null,DebTele text not null,DebMob text not null,DebEMail text not null,CretDate text not null,OutDis text not null,RemDis text not null,TownCode text not null,AreaCode text not null,DebCatCode text not null,DbGrCode text not null,DebClsCode text not null,Status text not null,DebLylty text not null,DealCode text not null,AddUser text not null,AddDateDEB text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,CrdPeriod text not null,ChkCrdPrd text not null,CrdLimit text not null,ChkCrdLmt text not null,RepCode text not null,RankCode text not null,txndate text not null,TranBatch text not null,DebSumary text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_CONTROL
					+ "(fcontrol_id integer primary key autoincrement,ComName text not null,ComAdd1 text not null,ComAdd2 text not null,ComAdd3 text not null,comtel1 text not null,comtel2 text not null,comfax1 text not null,comemail text not null,comweb text not null,confyear text not null,contyear text not null,comRegNo text not null,ConfTxn text not null,ContTxn text not null,Crystalpath text not null,VatCmTaxNo text not null,NbtCmTaxNo text not null,SysId text not null,DealCode text not null,basecur text not null,BalgCrLm text not null,conage1 text not null,conage2 text not null,conage3 text not null,conage4 text not null,conage5 text not null,conage6 text not null,conage7 text not null,conage8 text not null,conage9 text not null,conage10 text not null,conage11 text not null,conage12 text not null,conage13 text not null,conage14 text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_COMPANY_SETTING
					+ "(fcomset_id integer primary key autoincrement,cSettingsCode text not null,cSettingGrp text not null,cLocationChar text not null,cCharVal text not null,nNumVal text not null,cRemarks text not null,nType text not null,bUpdateFlag text not null,cCompanyCode text not null,recordid text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_DETAILS
					+ "(invdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,Itemcode text not null,Txnseqno text not null,SellPrice text not null,BSellPrice text not null,TSellPrice text not null,BTSellPrice text not null,CostPrice text not null,CaseQty text not null,Type text not null,PiceQty text not null,Qty text not null,BalQty text not null,DisPer text not null,DisAmt text not null,BDisAmt text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,ReaCode text not null,Linkrec text not null,RecordId text not null,itemDescription text not null,refInvoiceDetNo text not null,refInvoiceDetCode text not null,refInvitemCaseQty text not null,refInvStockOrderNo text not null,invdetSync text not null,invsysdate text not null,itemdisper text not null,itemdisperval text not null,reasonCode  text not null,reasonDesc  text not null,itemUnitPrice text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_HEADER
					+ "(invhead_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,InvType text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,RepCode text not null,AreaCode text not null,RouteCode text not null,DebCode text not null,LocCode text not null,Remarks text not null,CostCode text not null,CurCode text not null,CurRate text not null,TxnType text not null,InvAmt text not null,OutDis text not null,InvDis text not null,TotMkrAmt text not null,UnOvAmt text not null,TotalDis text not null,TotalAmt text not null,AddUser text not null,AddDateInvHead text not null,AddMach text not null,prtcopy text not null,RecordId text not null,timestamp_column text not null,refInvoiceHeaderNo text not null,refInvoiceHeaderCode text not null,invhedSync text not null,outDisVal text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTE
					+ "(route_id integer primary key autoincrement,RepCode text not null,RouteCode text not null,RouteName text not null,RecordId text not null,AddDate text not null,AreaCode text not null,DealCode text not null,FreqNo text not null,Km text not null,MinProcall text not null,RDAloRate text not null,RDTarget text not null,Remarks text not null,Status text not null,Tonnage text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTEDET
					+ "(fRouteDet_id integer primary key autoincrement,RecordId text not null,DebCode text not null,RouteCode text not null);");

			mydb.execSQL("create table if not exists "
					+ BANK_DETAILS
					+ "(bankre_id integer primary key autoincrement,RecordId text not null,bankcode text not null,bankname text not null,bankaccno text not null,Branch text not null,bankadd1 text not null,bankadd2 text not null,AddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_ORD_REASON
					+ "(freason_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,ReaCode text not null,ReaName text not null,ReaTcode text not null,RecordId text not null,Type text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_EXPENSE
					+ "(uexp_id integer primary key autoincrement,ExpCode text not null,ExpGrpCode text not null,ExpName text not null,RecordId text not null,Status text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ TOWN_DETAILS
					+ "(townre_id integer primary key autoincrement,RecordId text not null,TownCode text not null,TownName text not null,DistrCode text not null,AddDate text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ MERCH_DETAILS
					+ "(merchre_id integer primary key autoincrement,RecordId text not null,MerchCode text not null,MerchName text not null,AddUser text not null,AddMach text not null,AddDate text not null);");

			// New Master Tables
			mydb.execSQL("create table if not exists "
					+ FTRGCAPUL
					+ "(ftrg_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,DealCode text not null,Month text not null,Qty text not null,RecordId text not null,RepCode text not null,SKUCode text not null,Year text not null);");

			mydb.execSQL("create table if not exists "
					+ FTYPE
					+ "(ftype_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,TypeCode text not null,TypeName text not null);");

			mydb.execSQL("create table if not exists "
					+ FSUBBRAND
					+ "(fsubbrand_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,SBrandCode text not null,SBrandName text not null);");

			mydb.execSQL("create table if not exists "
					+ FGROUP
					+ "(fgroup_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,GroupCode text not null,GroupName text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ FSKU
					+ "(fsku_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,BrandCode text not null,GroupCode text not null,ItemStatus text not null,MustSale text not null,NOUCase text not null,OrdSeq text not null,RecordId text not null,SBrandCode text not null,SKUCode text not null,SkuName text not null,SkuSizCode text not null,Tonnage text not null,TypeCode text not null,Unit text not null);");

			mydb.execSQL("create table if not exists "
					+ FBRAND
					+ "(fbrand_id integer primary key autoincrement,AddMach text not null,AddUser text not null,BrandCode text not null,BrandName text not null,RecordId text not null);");

			// Stock Orders
			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_INVOICESUMERY
					+ "(remprepinv_id integer primary key autoincrement,repusername text not null,repprefix text not null,tempRepInvNoCode text not null,tempRepInvSerial text not null,invoiceComplete text not null,activeInvoice text not null,activeInvoiceValue text not null,activeInvItemDiscount text not null,activeInvCusDiscount text not null,activeInvCusDiscountValue text not null,InvoiceCustomerCode text not null,InvoiceCustomerName text not null,InvoiceSynchState text not null,recordDate text not null,recordSynchDate text not null,invlateststate text not null,activeInvoiceReturnValue text not null,activeInvoiceRemarks text not null,invoiceNoOfItems text not null,invoiceRef text not null,invoiceRefStl text not null,invoicedelidate text not null,invManuRefNo text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_HEAD
					+ "(stohed_id integer primary key autoincrement,AddMach text not null,AddUser text not null,AreaCode text not null,CostCode text not null,CurCode text not null,CurRate text not null,DealCode text not null,DebCode text not null,InvAmt text not null,InvDis text not null,InvFlg text not null,LocCode text not null,ManuRef text not null,OutDis text not null,RecordId text not null,RefNo text not null,Remarks text not null,RepCode text not null,RouteCode text not null,TotMkrAmt text not null,TotalAmt text not null,TotalDis text not null,TranBatch text not null,TxnType text not null,UnOvAmt text not null,prtcopy text not null,TxnDate text not null,stOrderComplete text not null,stordhedSync text not null,outDisVal text not null,ohAddDate text not null,delvDate text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_DETAIL
					+ "(stodet_id integer primary key autoincrement,Amt text not null,BAmt text not null,BDisAmt text not null,BSellPrice text not null,BTSellPrice text not null,BTaxAmt text not null,BalQty text not null,CaseQty text not null,CostPrice text not null,DisAmt text not null,DisPer text not null,Itemcode text not null,PiceQty text not null,Qty text not null,ReaCode text not null,RecordId text not null,RefNo text not null,SellPrice text not null,SeqNo text not null,TSellPrice text not null,TaxAmt text not null,TxnType text not null,Txnseqno text not null,Type text not null,TxnDate text not null,storddetSync text not null,itemdisper text not null,itemdisperval text not null,reasonDesc text not null,odAddDate text not null,itemUnitPrice text not null,caseUnitsQty text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMPSTOCK_ORDER_DETAIL
					+ "(invdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,Itemcode text not null,Txnseqno text not null,SellPrice text not null,BSellPrice text not null,TSellPrice text not null,BTSellPrice text not null,CostPrice text not null,CaseQty text not null,Type text not null,PiceQty text not null,Qty text not null,BalQty text not null,DisPer text not null,DisAmt text not null,BDisAmt text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,ReaCode text not null,Linkrec text not null,RecordId text not null,itemDescription text not null,refInvoiceDetNo text not null,refInvoiceDetCode text not null,refInvitemCaseQty text not null,refInvStockOrderNo text not null,refReasondetails text not null,itemdisper text not null,itemdisperval text not null,odtAddDate text not null,itemUnitPrice text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMPSTOCK_ORDER_HEAD
					+ "(invhead_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,InvType text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,RepCode text not null,AreaCode text not null,RouteCode text not null,DebCode text not null,LocCode text not null,Remarks text not null,CostCode text not null,CurCode text not null,CurRate text not null,TxnType text not null,InvAmt text not null,OutDis text not null,InvDis text not null,TotMkrAmt text not null,UnOvAmt text not null,TotalDis text not null,TotalAmt text not null,AddUser text not null,AddDateInvHead text not null,AddMach text not null,prtcopy text not null,RecordId text not null,timestamp_column text not null,refInvoiceHeaderNo text not null,refInvoiceHeaderCode text not null);");

			// Stock Loading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEAD
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null,stlhedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAIL
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,stldetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARY
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_COMPANY_BRANCH
					+ "(fcombra_id integer primary key autoincrement,BranchCode text not null,RecordId text not null,cSettingsCode text not null,nNumVal text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_SAL_REP
					+ "(fsalrep_id integer primary key autoincrement,ASECode text not null,AreaCode text not null,DealCode text not null,RecordId text not null,RepCode text not null,RepPrefix text not null,RepTCode text not null,repPhoneNo text not null,RepName text not null,RepEMail text not null,RepMob text not null);");

			// Stock UnLoading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null,stlhedunSync text not null,IntangFlg text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,stldetunSync text not null,IntangFlg text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYUN
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			// Stock Damage
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,CostCode text not null,ReaCode text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,ItemType text not null,stldmhedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,reaCode text not null,stldmdetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYDAM
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			// Cash / Cheque Receipt
			mydb.execSQL("create table if not exists "
					+ TEMP_RECEIPT_SUMMARY
					+ "(tempReceipt_id integer primary key autoincrement,treceiptusername text not null,treceiptprefix text not null,treceiptCode text not null,treceiptSerial text not null,treceiptRefNo text not null,treceiptComplete text not null,treceiptActive text not null,treceiptManualno text not null,treceiptstartDate text not null,treceiptCusno text not null,treceiptCusName text not null,treceiptPayType text not null,treceiptChequeno text not null,treceiptChequeDate text not null,treceiptBankNo text not null,treceiptBankName text not null,treceiptReceiptAmt text not null,treceiptReceiptBalAmt text not null,treceiptRemark text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_HEADER
					+ "(reched_id integer primary key autoincrement,RefNo text not null,ManuRef text not null,SaleRefNo text not null,RepCode text not null,TxnType text not null,Chqno text not null,ChqDate text not null,TxnDate text not null,CurCode text not null,CurRate text not null,DebCode text not null,TotalAmt text not null,BTotalAmt text not null,BankCur text not null,BankRate text not null,BankAmt text not null,BankCharge text not null,BBankChg text not null,GnLsCal text not null,DbAcc text not null,PayType text not null,PrtCopy text not null,GlPost text not null,Remarks text not null,CardSlipNo text not null,ExpDate text not null,CrdTypCode text not null,CCBankAmt text not null,GlBatch text not null,AddUser text not null,AddMach text not null,AddrecDate text not null,recipthedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_DETAILS
					+ "(RecDet_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,SaleRefNo text not null,ManuRef text not null,TxnType text not null,TxnDate text not null,DtxnDate text not null,DtxnType text not null,DCurCode text not null,DCurRate text not null,OCurRate text not null,RepCode text not null,Amt text not null,BAmt text not null,GainLosAmt text not null,BnkChgs text not null,BBnkChgs text not null,AloAmt text not null,OvPayAmt text not null,OvPayBal text not null,reciptdetSync text not null,recsysdate text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_INVOICES
					+ "(recinv_id integer primary key autoincrement,RecordId text not null,RefNo text not null,RefInv text not null,SaleRefNo text not null,ManuRef text not null,TxnType	text not null,TxnDate text not null,CurCode text not null,CurRate text not null,DebCode text not null,RepCode text not null,TaxComCode text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,TotBal text not null,TotBal1 text not null,OvPayAmt text not null,Remarks text not null,CrAcc text not null,PrtCopy text not null,GlPost text not null,glbatch text not null,AddUser text not null,AddDate	text not null,AddMach	text not null,RefNo1	text not null);");

			// Adjustment
			mydb.execSQL("create table if not exists "
					+ TEMP_ADJUSTMENT_SUMMARY
					+ "(adjustsum_id integer primary key autoincrement,username text not null,refCode text not null,refSerial text not null,currentState text not null,activeMode text not null,LocCode text not null,LocName text not null,TotalAmount text not null,ManuRefNo text not null,AdjustTxnType text not null);");

			mydb.execSQL("create table if not exists "
					+ ADJUST_ADDITION_DETAILS
					+ "(fadjdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,ReaCode text not null,ItemName text not null,QOH text not null,ReaName text not null,CaseUnits text not null,CasePrice text not null,adjDetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ ADJUST_ADDITION_HEADER
					+ "(fadjhed_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,CostCode text not null,ManuRef text not null,DealCode text not null,RefNo2 text not null,TxnType text not null,TotalAmt text not null,Remarks text not null,LocCode text not null,ReaCode text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDate text not null,AddMach text not null,ItemType text not null,adjHedSync text not null);");

			// Day Expence
			mydb.execSQL("create table if not exists "
					+ TEMP_DAYEXPENSE_SUMMARY
					+ "(dexpsum_id integer primary key autoincrement,dexprepusername text not null,dexprepprefix text not null,dexprefcode text not null,dexprefnoserial text not null,dexpreComplete text not null,dexpreActive text not null,dexprefnocode text not null,dexpremark text not null,amountTot text not null);");

			mydb.execSQL("create table if not exists "
					+ DAYEXPENSE_HEADER
					+ "(dexphed_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,RepName text not null,DealCode text not null,CostCode text not null,RepCode text not null,RegCode text not null,AreaCode text not null,Remarks text not null,AddUser text not null,AddDate text not null,AddMach text not null,TranBatch text not null);");

			mydb.execSQL("create table if not exists "
					+ DAYEXPENSE_DETAILS
					+ "(sdb_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,SeqNo text not null,ExpCode text not null,Amt text not null,ExpName text not null);");

			// None Productive Calls
			mydb.execSQL("create table if not exists "
					+ DAILY_NONE_PRDCALLS_HEAD
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,DebCode text not null,DebName text not null,Status text not null,stldmhedSync text not null,Reason text not null);");
	
			// None Productive Calls For Sales Order
			mydb.execSQL("create table if not exists "
					+ DAILY_NONE_PRDCALLS_HEADSO
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,DebCode text not null,DebName text not null,Status text not null,stldmhedSync text not null,Reason text not null);");
				
		} catch (Exception e) {
		}
		new DownloadAdministrative().execute();

	}

	// DownloadJSON AsyncTask
	private class DownloadAdministrative extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_Settings.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		// *****************Background Process**************************
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// *****************Download Available Data Bases**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfdblist.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("GetdatabaseNamesResult");
				Log.v(TAG, "Array Length Server DB :" + jsonArray.length());
				for (int i = 0; i < jsonArray.length(); i++) {
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowdblist = new ContentValues();
					Cursor sdblistrows = null;
					try {
						sdblistrows = mydb.query(SERVER_DB_LIST, null,
								"sdbname ='" + sdbname + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (sdblistrows != null) {
						if (sdblistrows.getCount() >= 1) {
							while (sdblistrows.moveToNext()) {
								Log.v(TAG, "Excisting fServer DB 1 :" + sdbname);
							}
						} else {
							Log.v(TAG, "DB 1:" + sdbname.trim());
							newrowdblist.put("sdbname", sdbname.trim());
							mydb.insert(SERVER_DB_LIST, null, newrowdblist);
							sdblistrows.close();
							mydb.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength : " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfdblist.close();

			} catch (Exception e) {
			}
			// ******Download Available fItemLoc details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL jsonfItemLoc = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItemLoc/mobile123"
								+ "/" + serverDbName);
				URLConnection jcfItemLoc = jsonfItemLoc.openConnection();
				BufferedReader readerfItemLoc = new BufferedReader(
						new InputStreamReader(jcfItemLoc.getInputStream()));

				String linefItemLoc = readerfItemLoc.readLine();

				JSONObject jsonResponsefItemLoc = new JSONObject(linefItemLoc);

				JSONArray jsonArrayfItemLoc = jsonResponsefItemLoc
						.getJSONArray("fItemLocResult");
				Log.v(TAG,
						"Array Length fItemLoc :" + jsonArrayfItemLoc.length());
				for (int i = 0; i < jsonArrayfItemLoc.length(); i++) {
					JSONObject jObjectfItemLoc = (JSONObject) jsonArrayfItemLoc
							.get(i);
					String ItemCodeFI = jObjectfItemLoc.getString("ItemCode");
					String LocCodeFI = jObjectfItemLoc.getString("LocCode");
					String QOHFI = jObjectfItemLoc.getString("QOH");
					RecordIdFI = jObjectfItemLoc.getString("RecordId");
					RecordIdFI = RecordIdFI.trim();
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemLoc = new ContentValues();
					Cursor fItemLocrows = null;
					try {
						String queryfil = "SELECT LocCode,RecordId from fItemLoc Where RecordId ='"
								+ RecordIdFI + "'";
						fItemLocrows = mydb.rawQuery(queryfil, null);
					} catch (Exception e) {
					}
					if (fItemLocrows != null) {
						if (fItemLocrows.getCount() >= 1) {
							while (fItemLocrows.moveToNext()) {
								Log.v(TAG, "Excisting fItemLocrows 1 :"
										+ RecordIdFI);
								String chkLocCode = fItemLocrows.getString(0);
								String chkRecordId = fItemLocrows.getString(1);

								if (chkLocCode.equals("MS")) {
									Log.v(TAG, "Update fItemLoc QOH: "
											+ chkRecordId);
									newrowfItemLoc.put("QOH", QOHFI.trim());
									mydb.update(ITEM_LOC_DETAILS,
											newrowfItemLoc, "RecordId ='"
													+ chkRecordId + "'", null);
								}
							}
						} else {
							Log.v(TAG, "fItemLoc 1:" + RecordIdFI);
							newrowfItemLoc.put("LocCode", LocCodeFI.trim());
							newrowfItemLoc.put("ItemCode", ItemCodeFI.trim());
							newrowfItemLoc.put("QOH", QOHFI.trim());
							newrowfItemLoc.put("RecordId", RecordIdFI);
							newrowfItemLoc.put("timestamp_column",
									getCurrentTimeString().toString());
							newrowfItemLoc.put("syncRec", "0");
							mydb.insert(ITEM_LOC_DETAILS, null, newrowfItemLoc);
							fItemLocrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 1: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItemLoc.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItemPri**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItemPri/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfItemPri = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItemPri.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfItemPri = jsonResponse
						.getJSONArray("fItemPriResult");
				Log.v(TAG,
						"Array Length fItemPri :" + jsonArrayfItemPri.length());
				for (int i = 0; i < jsonArrayfItemPri.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfItemPri.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String PrilCode = jObject.getString("PrilCode");
					String Price = jObject.getString("Price");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String Txnuser = jObject.getString("Txnuser");
					String TxnMach = jObject.getString("TxnMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemPri = new ContentValues();
					Cursor newrowfItemPriuserrows = null;
					try {
						newrowfItemPriuserrows = mydb.query(ITEM_PRICE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfItemPriuserrows != null) {
						if (newrowfItemPriuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfItemPriuserrows 2");
						} else {
							Log.v(TAG, "fItemPri 2:" + RecordId.trim());
							newrowfItemPri.put("SKUCode", SKUCode.trim());
							newrowfItemPri.put("ItemCode", ItemCode.trim());
							newrowfItemPri.put("PrilCode", PrilCode.trim());
							newrowfItemPri.put("PriRDate",
									getCurrentTimeString().toString());
							newrowfItemPri.put("Price", Price.trim());
							newrowfItemPri.put("AddUser", AddUser.trim());
							newrowfItemPri.put("AddDateIP",
									getCurrentTimeString().toString());
							newrowfItemPri.put("AddMach", AddMach.trim());
							newrowfItemPri.put("Txnuser", Txnuser.trim());
							newrowfItemPri.put("TxnDate",
									getCurrentTimeString().toString());
							newrowfItemPri.put("TxnMach", TxnMach.trim());
							newrowfItemPri.put("RecordId", RecordId.trim());
							mydb.insert(ITEM_PRICE, null, newrowfItemPri);
							newrowfItemPriuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 2: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItemPri.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItems**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItems/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfItems = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItems.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfItems = jsonResponse
						.getJSONArray("fItemsResult");
				Log.v(TAG, "Array Length fItems :" + jsonArrayfItems.length());
				for (int i = 0; i < jsonArrayfItems.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfItems.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String MapCode = jObject.getString("MapCode");
					String ItemName = jObject.getString("ItemName");
					String VenPcode = jObject.getString("VenPcode");
					String GroupCode = jObject.getString("GroupCode");
					String TypeCode = jObject.getString("TypeCode");
					String TaxComCode = jObject.getString("TaxComCode");
					String UnitCode = jObject.getString("UnitCode");
					String SkuSizCode = jObject.getString("SkuSizCode");
					String ItemStatus = jObject.getString("ItemStatus");
					String ReOrderLvl = jObject.getString("ReOrderLvl");
					String ReOrderQty = jObject.getString("ReOrderQty");
					String AvgPrice = jObject.getString("AvgPrice");
					String PurAcc = jObject.getString("PurAcc");
					String PurRetAcc = jObject.getString("PurRetAcc");
					String SVATAcc = jObject.getString("SVATAcc");
					String ExportAcc = jObject.getString("ExportAcc");
					String IndrExAcc = jObject.getString("IndrExAcc");
					String SalAcc = jObject.getString("SalAcc");
					String SalRetAcc = jObject.getString("SalRetAcc");
					String DisAcc = jObject.getString("DisAcc");
					String ClsStkAcc = jObject.getString("ClsStkAcc");
					String StkInAcc = jObject.getString("StkInAcc");
					String PrilCode = jObject.getString("PrilCode");
					String BrandCode = jObject.getString("BrandCode");
					String SBrandCode = jObject.getString("SBrandCode");
					String NOUCase = jObject.getString("NOUCase");
					String OrdSeq = jObject.getString("OrdSeq");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					String MustSale = jObject.getString("MustSale");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItems = new ContentValues();
					Cursor newrowfItemListuserrows = null;
					try {
						newrowfItemListuserrows = mydb.query(ITEMS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfItemListuserrows != null) {
						if (newrowfItemListuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfItemListuserrows 3");
						} else {

							Log.v(TAG, "fItems 3:" + RecordId.trim());
							newrowfItems.put("SKUCode", SKUCode.trim());
							newrowfItems.put("ItemCode", ItemCode.trim());
							newrowfItems.put("MapCode", MapCode.trim());
							newrowfItems.put("ItemName", ItemName.trim());
							newrowfItems.put("VenPcode", VenPcode.trim());
							newrowfItems.put("GroupCode", GroupCode.trim());
							newrowfItems.put("TypeCode", TypeCode.trim());
							newrowfItems.put("TaxComCode", TaxComCode.trim());
							newrowfItems.put("UnitCode", UnitCode.trim());
							newrowfItems.put("SkuSizCode", SkuSizCode.trim());
							newrowfItems.put("ItemStatus", ItemStatus.trim());
							newrowfItems.put("ReOrderLvl", ReOrderLvl.trim());
							newrowfItems.put("ReOrderQty", ReOrderQty.trim());
							newrowfItems.put("AvgPrice", AvgPrice.trim());
							newrowfItems.put("PurAcc", PurAcc.trim());
							newrowfItems.put("PurRetAcc", PurRetAcc.trim());
							newrowfItems.put("SVATAcc", SVATAcc.trim());
							newrowfItems.put("ExportAcc", ExportAcc.trim());
							newrowfItems.put("IndrExAcc", IndrExAcc.trim());
							newrowfItems.put("SalAcc", SalAcc.trim());
							newrowfItems.put("SalRetAcc", SalRetAcc.trim());
							newrowfItems.put("DisAcc", DisAcc.trim());
							newrowfItems.put("ClsStkAcc", ClsStkAcc.trim());
							newrowfItems.put("StkInAcc", StkInAcc.trim());
							newrowfItems.put("PrilCode", PrilCode.trim());
							newrowfItems.put("BrandCode", BrandCode.trim());
							newrowfItems.put("SBrandCode", SBrandCode.trim());
							newrowfItems.put("NOUCase", NOUCase.trim());
							if(OrdSeq.length()== 1){
								OrdSeq = "0" + OrdSeq;
							}
							
							newrowfItems.put("OrdSeq", OrdSeq.trim());
							newrowfItems.put("AddUser", AddUser.trim());
							newrowfItems.put("AddDatefitem",
									getCurrentTimeString().toString());
							newrowfItems.put("AddMach", AddMach.trim());
							newrowfItems.put("RecordId", RecordId.trim());
							newrowfItems.put("timestamp_column ",
									getCurrentTimeString().toString());
							newrowfItems.put("MustSale ", MustSale.trim());
							mydb.insert(ITEMS, null, newrowfItems);
							newrowfItemListuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 3: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItems.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download Fdebtor**************

			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/Fdebtor/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFdebtor = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFdebtor.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFdebtor = jsonResponse
						.getJSONArray("FdebtorResult");
				Log.v(TAG, "Array Length Fdebtor :" + jsonArrayFdebtor.length());
				for (int i = 0; i < jsonArrayFdebtor.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFdebtor.get(i);
					String DebCode = jObject.getString("DebCode");
					String DebName = jObject.getString("DebName");
					String DebAdd1 = jObject.getString("DebAdd1");
					String DebAdd2 = jObject.getString("DebAdd2");
					String DebAdd3 = jObject.getString("DebAdd3");
					String DebTele = jObject.getString("DebTele");
					String DebMob = jObject.getString("DebMob");
					String DebEMail = jObject.getString("DebEMail");
					String OutDis = jObject.getString("OutDis");
					String RemDis = jObject.getString("RemDis");
					String TownCode = jObject.getString("TownCode");
					String AreaCode = jObject.getString("AreaCode");
					String DebCatCode = jObject.getString("DebCatCode");
					String DbGrCode = jObject.getString("DbGrCode");
					String DebClsCode = jObject.getString("DebClsCode");
					String Status = jObject.getString("Status");
					String DebLylty = jObject.getString("DebLylty");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					String CrdPeriod = jObject.getString("CrdPeriod");
					String ChkCrdPrd = jObject.getString("ChkCrdPrd");
					String CrdLimit = jObject.getString("CrdLimit");
					String ChkCrdLmt = jObject.getString("ChkCrdLmt");
					String RepCode = jObject.getString("RepCode");
					String RankCode = jObject.getString("RankCode");
					String TranBatch = jObject.getString("TranBatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfdebtord = new ContentValues();
					Cursor fdebtorduserrows = null;
					try {
						fdebtorduserrows = mydb.query(ITEM_DEBTOR, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fdebtorduserrows != null) {
						if (fdebtorduserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fdebtorduserrows 4");
						} else {
							Log.v(TAG, "Fdebtor 4:" + RecordId.trim());
							newrowfdebtord.put("DebCode", DebCode.trim());
							newrowfdebtord.put("DebName", DebName.trim());
							newrowfdebtord.put("DebAdd1", DebAdd1.trim());
							newrowfdebtord.put("DebAdd2", DebAdd2.trim());
							newrowfdebtord.put("DebAdd3", DebAdd3.trim());
							newrowfdebtord.put("DebTele", DebTele.trim());
							newrowfdebtord.put("DebMob", DebMob.trim());
							newrowfdebtord.put("DebEMail", DebEMail.trim());
							newrowfdebtord.put("CretDate",
									getCurrentTimeString().toString());
							newrowfdebtord.put("OutDis", OutDis.trim());
							newrowfdebtord.put("RemDis", RemDis.trim());
							newrowfdebtord.put("TownCode", TownCode.trim());
							newrowfdebtord.put("AreaCode", AreaCode.trim());
							newrowfdebtord.put("DebCatCode", DebCatCode.trim());
							newrowfdebtord.put("DbGrCode", DbGrCode.trim());
							newrowfdebtord.put("DebClsCode", DebClsCode.trim());
							newrowfdebtord.put("Status", Status.trim());
							newrowfdebtord.put("DebLylty", DebLylty.trim());
							newrowfdebtord.put("DealCode", DealCode.trim());
							newrowfdebtord.put("AddUser", AddUser.trim());
							newrowfdebtord.put("AddDateDEB",
									getCurrentTimeString().toString());
							newrowfdebtord.put("AddMach", AddMach.trim());
							newrowfdebtord.put("RecordId", RecordId.trim());
							newrowfdebtord.put("timestamp_column",
									getCurrentTimeString().toString());
							newrowfdebtord.put("CrdPeriod", CrdPeriod.trim());
							newrowfdebtord.put("ChkCrdPrd", ChkCrdPrd.trim());
							newrowfdebtord.put("CrdLimit", CrdLimit.trim());
							newrowfdebtord.put("ChkCrdLmt", ChkCrdLmt.trim());
							newrowfdebtord.put("RepCode", RepCode.trim());
							newrowfdebtord.put("RankCode", RankCode.trim());
							newrowfdebtord.put("txndate",
									getCurrentTimeString().toString());
							newrowfdebtord.put("TranBatch", TranBatch.trim());
							String DebSumStr = DebCode.trim() + " : "
									+ DebName.trim();
							newrowfdebtord.put("DebSumary", DebSumStr);

							mydb.insert(ITEM_DEBTOR, null, newrowfdebtord);
							fdebtorduserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 4: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFdebtor.close();

			} catch (Exception e) {
				// Toast.makeText(this, evtoString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fControl**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fControl/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfControl = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfControl.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfControl = jsonResponse
						.getJSONArray("fControlResult");
				Log.v(TAG,
						"Array Length Fdebtor :" + jsonArrayfControl.length());
				for (int i = 0; i < jsonArrayfControl.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfControl.get(i);
					String ComName = jObject.getString("ComName");
					String ComAdd1 = jObject.getString("ComAdd1");
					String ComAdd2 = jObject.getString("ComAdd2");
					String ComAdd3 = jObject.getString("ComAdd3");
					String comtel1 = jObject.getString("comtel1");
					String comtel2 = jObject.getString("comtel2");
					String comfax1 = jObject.getString("comfax1");
					String comemail = jObject.getString("comemail");
					String comweb = jObject.getString("comweb");
					// String confyear = jObject.getString("confyear");
					// String contyear = jObject.getString("contyear");
					String comRegNo = jObject.getString("comRegNo");
					// String ConfTxn = jObject.getString("ConfTxn");
					// String ContTxn = jObject.getString("ContTxn");
					String Crystalpath = jObject.getString("Crystalpath");
					String VatCmTaxNo = jObject.getString("VatCmTaxNo");
					String NbtCmTaxNo = jObject.getString("NbtCmTaxNo");
					String SysId = jObject.getString("SysId");
					String DealCode = jObject.getString("DealCode");
					String basecur = jObject.getString("basecur");
					String BalgCrLm = jObject.getString("BalgCrLm");
					String conage1 = jObject.getString("conage1");
					String conage2 = jObject.getString("conage2");
					String conage3 = jObject.getString("conage3");
					String conage4 = jObject.getString("conage4");
					String conage5 = jObject.getString("conage5");
					String conage6 = jObject.getString("conage6");
					String conage7 = jObject.getString("conage7");
					String conage8 = jObject.getString("conage8");
					String conage9 = jObject.getString("conage9");
					String conage10 = jObject.getString("conage10");
					String conage11 = jObject.getString("conage11");
					String conage12 = jObject.getString("conage12");
					String conage13 = jObject.getString("conage13");
					String conage14 = jObject.getString("conage14");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfcontrol = new ContentValues();
					Cursor fcontroluserrows = null;
					try {
						fcontroluserrows = mydb.query(ITEM_CONTROL, null,
								"SysId ='" + SysId.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (fcontroluserrows != null) {
						if (fcontroluserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fcontroluserrows 5");
						} else {
							Log.v(TAG, "fControl 5:" + SysId.trim());
							newrowfcontrol.put("ComName", ComName.trim());
							newrowfcontrol.put("ComAdd1", ComAdd1.trim());
							newrowfcontrol.put("ComAdd2", ComAdd2.trim());
							newrowfcontrol.put("ComAdd3", ComAdd3.trim());
							newrowfcontrol.put("comtel1", comtel1.trim());
							newrowfcontrol.put("comtel2", comtel2.trim());
							newrowfcontrol.put("comfax1", comfax1.trim());
							newrowfcontrol.put("comemail", comemail.trim());
							newrowfcontrol.put("comweb", comweb.trim());
							newrowfcontrol.put("confyear",
									getCurrentTimeString().toString());
							newrowfcontrol.put("contyear",
									getCurrentTimeString().toString());
							newrowfcontrol.put("comRegNo", comRegNo.trim());
							newrowfcontrol.put("ConfTxn",
									getCurrentTimeString().toString());
							newrowfcontrol.put("ContTxn",
									getCurrentTimeString().toString());
							newrowfcontrol.put("Crystalpath",
									Crystalpath.trim());
							newrowfcontrol.put("VatCmTaxNo", VatCmTaxNo.trim());
							newrowfcontrol.put("NbtCmTaxNo", NbtCmTaxNo.trim());
							newrowfcontrol.put("SysId", SysId.trim());
							newrowfcontrol.put("DealCode", DealCode.trim());
							newrowfcontrol.put("basecur", basecur.trim());
							newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
							newrowfcontrol.put("conage1", conage1.trim());
							newrowfcontrol.put("conage2", conage2.trim());
							newrowfcontrol.put("conage3", conage3.trim());
							newrowfcontrol.put("conage4", conage4.trim());
							newrowfcontrol.put("conage5", conage5.trim());
							newrowfcontrol.put("conage6", conage6.trim());
							newrowfcontrol.put("conage7", conage7.trim());
							newrowfcontrol.put("conage8", conage8.trim());
							newrowfcontrol.put("conage9", conage9.trim());
							newrowfcontrol.put("conage10", conage10.trim());
							newrowfcontrol.put("conage11", conage11.trim());
							newrowfcontrol.put("conage12", conage12.trim());
							newrowfcontrol.put("conage13", conage13.trim());
							newrowfcontrol.put("conage14", conage14.trim());
							mydb.insert(ITEM_CONTROL, null, newrowfcontrol);
							fcontroluserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 5: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfControl.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fCompanySetting**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fCompanySetting/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanySetting = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanySetting.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfCompanySetting = jsonResponse
						.getJSONArray("fCompanySettingResult");
				Log.v(TAG, "Array Length fCompanySetting :"
						+ jsonArrayfCompanySetting.length());
				for (int i = 0; i < jsonArrayfCompanySetting.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfCompanySetting
							.get(i);

					String cSettingsCode = jObject.getString("cSettingsCode");
					String cSettingGrp = jObject.getString("cSettingGrp");
					String cLocationChar = jObject.getString("cLocationChar");
					String cCharVal = jObject.getString("cCharVal");
					String nNumVal = jObject.getString("nNumVal");
					String cRemarks = jObject.getString("cRemarks");
					String nType = jObject.getString("nType");
					String bUpdateFlag = jObject.getString("bUpdateFlag");
					String cCompanyCode = jObject.getString("cCompanyCode");
					String recordid = jObject.getString("recordid");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfCompanySetting = new ContentValues();
					Cursor fCompanySettingrows = null;
					try {
						fCompanySettingrows = mydb.query(ITEM_COMPANY_SETTING,
								null, "recordid ='" + recordid.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (fCompanySettingrows != null) {
						if (fCompanySettingrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fCompanySettingrows 6");
						} else {
							Log.v(TAG, "fCompanySetting 6:" + recordid.trim());
							newrowfCompanySetting.put("cSettingsCode",
									cSettingsCode.trim());
							newrowfCompanySetting.put("cSettingGrp",
									cSettingGrp.trim());
							newrowfCompanySetting.put("cLocationChar",
									cLocationChar.trim());
							newrowfCompanySetting.put("cCharVal",
									cCharVal.trim());
							newrowfCompanySetting
									.put("nNumVal", nNumVal.trim());
							newrowfCompanySetting.put("cRemarks",
									cRemarks.trim());
							newrowfCompanySetting.put("nType ", nType.trim());
							newrowfCompanySetting.put("bUpdateFlag",
									bUpdateFlag.trim());
							newrowfCompanySetting.put("cCompanyCode",
									cCompanyCode.trim());
							newrowfCompanySetting.put("recordid",
									recordid.trim());
							newrowfCompanySetting.put("timestamp_column",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_COMPANY_SETTING, null,
									newrowfCompanySetting);
							fCompanySettingrows.close();
						}
					}
					mydb.close();

				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 6: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfCompanySetting.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fArea**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fArea/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfArea = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfArea.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfArea = jsonResponse
						.getJSONArray("fAreaResult");
				Log.v(TAG, "Array Length fArea :" + jsonArrayfArea.length());
				for (int i = 0; i < jsonArrayfArea.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfArea.get(i);

					// String fAreaID = jObject.getString("fAreaID");
					String AreaCode = jObject.getString("AreaCode");
					String AreaName = jObject.getString("AreaName");
					String RegCode = jObject.getString("RegCode");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					// String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					// String timestamp_column =
					// jObject.getString("timestamp_column");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfArea = new ContentValues();
					Cursor fArearows = null;
					try {
						fArearows = mydb
								.query(ITEM_AREA, null, "RecordId ='"
										+ RecordId.trim() + "'", null, null,
										null, null);
					} catch (Exception e) {
					}
					if (fArearows != null) {
						if (fArearows.getCount() >= 1) {
							Log.v(TAG, "Excisting fArearows 7");
						} else {
							Log.v(TAG, "fArea 7:" + RecordId.trim());
							newrowfArea.put("AreaCode", AreaCode.trim());
							newrowfArea.put("AreaName", AreaName.trim());
							newrowfArea.put("RegCode", RegCode.trim());
							newrowfArea.put("DealCode", DealCode.trim());
							newrowfArea.put("AddUser", AddUser.trim());
							newrowfArea.put("AddDatefarea",
									getCurrentTimeString().toString());
							newrowfArea.put("AddMach", AddMach.trim());
							newrowfArea.put("RecordId", RecordId.trim());
							newrowfArea.put("timestamp_column",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_AREA, null, newrowfArea);
							fArearows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 7: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfArea.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fLocations**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fLocations/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfLocations = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfLocations.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfLocations = jsonResponse
						.getJSONArray("fLocationsResult");
				Log.v(TAG,
						"Array Length fLocations :"
								+ jsonArrayfLocations.length());
				for (int i = 0; i < jsonArrayfLocations.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfLocations
							.get(i);
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Address1 = jObject.getString("Address1");
					String Address2 = jObject.getString("Address2");
					String Address3 = jObject.getString("Address3");
					String Contact = jObject.getString("Contact");
					String EMail = jObject.getString("EMail");
					String FaxNo = jObject.getString("FaxNo");
					String LocCode = jObject.getString("LocCode");
					String LocName = jObject.getString("LocName");
					String LoctCode = jObject.getString("LoctCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String TeleNo = jObject.getString("TeleNo");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowflocation = new ContentValues();
					Cursor newrowflocationrows = null;
					try {
						newrowflocationrows = mydb.query(ITEM_LOCATION, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowflocationrows != null) {
						if (newrowflocationrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowflocationrows 8");
						} else {
							Log.v(TAG, "fLocations 8:" + RecordId.trim());
							newrowflocation.put("AddMach", AddMach.trim());
							newrowflocation.put("AddUser", AddUser.trim());
							newrowflocation.put("Address1", Address1.trim());
							newrowflocation.put("Address2", Address2.trim());
							newrowflocation.put("Address3", Address3.trim());
							newrowflocation.put("Contact", Contact.trim());
							newrowflocation.put("EMail", EMail.trim());
							newrowflocation.put("FaxNo", FaxNo.trim());
							newrowflocation.put("LocCode", LocCode.trim());
							newrowflocation.put("LocName", LocName.trim());
							newrowflocation.put("LoctCode", LoctCode.trim());
							newrowflocation.put("RecordId", RecordId.trim());
							newrowflocation.put("RepCode", RepCode.trim());
							newrowflocation.put("TeleNo", TeleNo.trim());
							newrowflocation.put("LocAddDate",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_LOCATION, null, newrowflocation);
							newrowflocationrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 8: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfLocations.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FCompanyBranch**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FCompanyBranch/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanyBranchResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanyBranchResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFCompanyBranch = jsonResponse
						.getJSONArray("FCompanyBranchResult");
				Log.v(TAG, "Array Length FCompanyBranch :"
						+ jsonArrayFCompanyBranch.length());
				for (int i = 0; i < jsonArrayFCompanyBranch.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFCompanyBranch
							.get(i);

					String BranchCode = jObject.getString("BranchCode");
					String RecordId = jObject.getString("RecordId");
					String cSettingsCode = jObject.getString("cSettingsCode");
					String nNumVal = jObject.getString("nNumVal");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfRepbranchrows = new ContentValues();
					Cursor newrowflRebranchprows = null;
					try {
						newrowflRebranchprows = mydb.query(INV_COMPANY_BRANCH,
								null, "RecordId ='" + RecordId.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (newrowflRebranchprows != null) {
						if (newrowflRebranchprows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowflRebranchprows 9");
						} else {
							Log.v(TAG,
									"FCompanyBranch 9:" + cSettingsCode.trim());
							newrowreaderfRepbranchrows.put("BranchCode",
									BranchCode.trim());
							newrowreaderfRepbranchrows.put("RecordId",
									RecordId.trim());
							newrowreaderfRepbranchrows.put("cSettingsCode",
									cSettingsCode.trim());
							newrowreaderfRepbranchrows.put("nNumVal",
									nNumVal.trim());

							mydb.insert(INV_COMPANY_BRANCH, null,
									newrowreaderfRepbranchrows);
							newrowflRebranchprows.close();
						}

						mydb.close();
					}
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 9: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfCompanyBranchResult.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fSalRep**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fSalRep/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfSalRepResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfSalRepResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfSalRep = jsonResponse
						.getJSONArray("fSalRepResult");
				Log.v(TAG, "Array Length fSalRep :" + jsonArrayfSalRep.length());
				for (int i = 0; i < jsonArrayfSalRep.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfSalRep.get(i);
					String ASECode = jObject.getString("ASECode");
					String AreaCode = jObject.getString("AreaCode");
					String DealCode = jObject.getString("DealCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String RepPrefix = jObject.getString("RepPrefix");
					String RepTCode = jObject.getString("RepTCode");
					String RepTele = jObject.getString("RepTele");
					String RepMob = jObject.getString("RepMob");
					String RepEMail = jObject.getString("RepEMail");
					String RepName = jObject.getString("RepName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfSalReprows = new ContentValues();
					Cursor newrowfSalReprows = null;
					try {
						newrowfSalReprows = mydb.query(INV_SAL_REP, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfSalReprows != null) {
						if (newrowfSalReprows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfSalReprows 10");
						} else {
							Log.v(TAG, "fSalRep 10:" + RepCode.trim());
							newrowreaderfSalReprows.put("ASECode",
									ASECode.trim());
							newrowreaderfSalReprows.put("AreaCode",
									AreaCode.trim());
							newrowreaderfSalReprows.put("DealCode",
									DealCode.trim());
							newrowreaderfSalReprows.put("RecordId",
									RecordId.trim());
							newrowreaderfSalReprows.put("RepCode",
									RepCode.trim());
							newrowreaderfSalReprows.put("RepPrefix",
									RepPrefix.trim());
							newrowreaderfSalReprows.put("RepTCode",
									RepTCode.trim());
							newrowreaderfSalReprows.put("repPhoneNo", RepTele);
							newrowreaderfSalReprows.put("RepMob", RepMob);
							newrowreaderfSalReprows.put("RepEMail", RepEMail);
							newrowreaderfSalReprows.put("RepName", RepName);

							mydb.insert(INV_SAL_REP, null,
									newrowreaderfSalReprows);
							newrowfSalReprows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 10: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfSalRepResult.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

		/*	// *****************Download FOrdHed**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FOrdHed/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfstordhed = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstordhed.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFOrdHed = jsonResponse
						.getJSONArray("FOrdHedResult");
				Log.v(TAG, "Array Length FOrdHed :" + jsonArrayFOrdHed.length());
				for (int i = 0; i < jsonArrayFOrdHed.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFOrdHed.get(i);

					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String AreaCode = jObject.getString("AreaCode");
					String CostCode = jObject.getString("CostCode");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DealCode = jObject.getString("DealCode");
					String DebCode = jObject.getString("DebCode");
					String InvAmt = jObject.getString("InvAmt");
					String InvDis = jObject.getString("InvDis");
					String InvFlg = jObject.getString("InvFlg");
					String LocCode = jObject.getString("LocCode");
					String ManuRef = jObject.getString("ManuRef");
					String OutDis = jObject.getString("OutDis");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String TotMkrAmt = jObject.getString("TotMkrAmt");
					String TotalAmt = jObject.getString("TotalAmt");
					String TotalDis = jObject.getString("TotalDis");
					String TranBatch = jObject.getString("TranBatch");
					String TxnType = jObject.getString("TxnType");
					String UnOvAmt = jObject.getString("UnOvAmt");
					String prtcopy = jObject.getString("prtcopy");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstordhed = new ContentValues();
					Cursor cursorfstordhed = null;
					try {
						cursorfstordhed = mydb.query(STOCK_ORDER_HEAD, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (cursorfstordhed != null) {
						if (cursorfstordhed.getCount() >= 1) {
							Log.v(TAG, "Excisting cursorfstordhed 11");
						} else {
							Log.v(TAG, "FOrdHed 11:" + RecordId.trim());
							
							newrowfstordhed.put("AddMach", AddMach.trim());
							newrowfstordhed.put("AddUser", AddUser.trim());
							newrowfstordhed.put("AreaCode", AreaCode.trim());
							newrowfstordhed.put("CostCode", CostCode.trim());
							newrowfstordhed.put("CurCode", CurCode.trim());
							newrowfstordhed.put("CurRate", CurRate.trim());
							newrowfstordhed.put("DealCode", DealCode.trim());
							newrowfstordhed.put("DebCode", DebCode.trim());
							newrowfstordhed.put("InvAmt", InvAmt.trim());
							newrowfstordhed.put("InvDis", InvDis.trim());
							newrowfstordhed.put("InvFlg", InvFlg.trim());
							newrowfstordhed.put("LocCode", LocCode.trim());
							newrowfstordhed.put("ManuRef", ManuRef.trim());
							newrowfstordhed.put("OutDis", OutDis.trim());
							newrowfstordhed.put("RecordId", RecordId.trim());
							newrowfstordhed.put("RefNo", RefNo.trim());
							newrowfstordhed.put("Remarks", Remarks.trim());
							newrowfstordhed.put("RepCode", RepCode.trim());
							newrowfstordhed.put("RouteCode", RouteCode.trim());
							newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
							newrowfstordhed.put("TotalAmt", TotalAmt.trim());
							newrowfstordhed.put("TotalDis", TotalDis.trim());
							newrowfstordhed.put("TranBatch", TranBatch.trim());
							newrowfstordhed.put("TxnType", TxnType.trim());
							newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
							newrowfstordhed.put("prtcopy", prtcopy.trim());
							newrowfstordhed.put("TxnDate", TxnDate.trim());
							newrowfstordhed.put("stOrderComplete", "0");
							newrowfstordhed.put("ohAddDate", TxnDate.trim());
							newrowfstordhed.put("stordhedSync", "1");
							newrowfstordhed.put("outDisVal", InvDis.trim());
							newrowfstordhed.put("delvDate", TxnDate.trim());
							mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
							cursorfstordhed.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 11: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfstordhed.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FOrddet**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FOrddet/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfstorddet = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstorddet.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFOrddet = jsonResponse
						.getJSONArray("FOrddetResult");
				Log.v(TAG, "Array Length FOrddet :" + jsonArrayFOrddet.length());
				for (int i = 0; i < jsonArrayFOrddet.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFOrddet.get(i);

					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BDisAmt = jObject.getString("BDisAmt");
					String BSellPrice = jObject.getString("BSellPrice");
					String BTSellPrice = jObject.getString("BTSellPrice");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String BalQty = jObject.getString("BalQty");
					String CaseQty = jObject.getString("CaseQty");
					String CostPrice = jObject.getString("CostPrice");
					String DisAmt = jObject.getString("DisAmt");
					String DisPer = jObject.getString("DisPer");
					String Itemcode = jObject.getString("Itemcode");
					String PiceQty = jObject.getString("PiceQty");
					String Qty = jObject.getString("Qty");
					String ReaCode = jObject.getString("ReaCode");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String SellPrice = jObject.getString("SellPrice");
					String SeqNo = jObject.getString("SeqNo");
					String TSellPrice = jObject.getString("TSellPrice");
					String TaxAmt = jObject.getString("TaxAmt");
					String TxnType = jObject.getString("TxnType");
					String Txnseqno = jObject.getString("Txnseqno");
					String Type = jObject.getString("Type");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstorddet = new ContentValues();
					Cursor cursorfstorddet = null;
					try {
						cursorfstorddet = mydb.query(STOCK_ORDER_DETAIL, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (cursorfstorddet != null) {
						if (cursorfstorddet.getCount() >= 1) {
							Log.v(TAG, "Excisting cursorfstorddet 12");
						} else {
							Log.v(TAG, "FOrddet 12:" + RecordId.trim());
   							newrowfstorddet.put("Amt", Amt.trim());
							newrowfstorddet.put("BAmt", BAmt.trim());
							newrowfstorddet.put("BDisAmt", BDisAmt.trim());
							newrowfstorddet.put("BSellPrice", BSellPrice.trim());
							newrowfstorddet.put("BTSellPrice",BTSellPrice.trim());
							newrowfstorddet.put("BTaxAmt", BTaxAmt.trim());
							newrowfstorddet.put("BalQty", BalQty.trim());
							newrowfstorddet.put("CaseQty", CaseQty.trim());
							newrowfstorddet.put("CostPrice", CostPrice.trim());
							newrowfstorddet.put("DisAmt", DisAmt.trim());
							newrowfstorddet.put("DisPer", DisPer.trim());
							newrowfstorddet.put("Itemcode", Itemcode.trim());
							newrowfstorddet.put("PiceQty", PiceQty.trim());
							newrowfstorddet.put("Qty", Qty.trim());
							newrowfstorddet.put("ReaCode", ReaCode.trim());
							newrowfstorddet.put("RecordId", RecordId.trim());
							newrowfstorddet.put("RefNo", RefNo.trim());
							newrowfstorddet.put("SellPrice", SellPrice.trim());
							newrowfstorddet.put("SeqNo", SeqNo.trim());
							newrowfstorddet.put("TSellPrice", TSellPrice.trim());
							newrowfstorddet.put("TaxAmt", TaxAmt.trim());
							newrowfstorddet.put("TxnType", TxnType.trim());
							newrowfstorddet.put("Txnseqno", Txnseqno.trim());
							newrowfstorddet.put("Type", Type.trim());
							newrowfstorddet.put("TxnDate", TxnDate.trim());
							newrowfstorddet.put("storddetSync", "0");
							newrowfstorddet.put("itemdisper", DisPer.trim());
							newrowfstorddet.put("itemdisperval", DisPer.trim());
							newrowfstorddet.put("reasonDesc", ReaCode.trim());
							newrowfstorddet.put("odAddDate", TxnDate.trim());
							mydb.insert(STOCK_ORDER_DETAIL, null,
									newrowfstorddet);
							cursorfstorddet.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 12: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfstorddet.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
*/
			// *****************Download fReason**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fReason/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfReason = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfReason.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfReason = jsonResponse
						.getJSONArray("fReasonResult");
				Log.v(TAG, "Array Length fReason :" + jsonArrayfReason.length());
				for (int i = 0; i < jsonArrayfReason.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfReason.get(i);

					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String ReaCode = jObject.getString("ReaCode");
					String ReaName = jObject.getString("ReaName");
					String ReaTcode = jObject.getString("ReaTcode");
					String RecordId = jObject.getString("RecordId");
					String Type = jObject.getString("Type");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfReason = new ContentValues();
					Cursor fReasonSettingrows = null;
					try {
						fReasonSettingrows = mydb.query(SALES_ORD_REASON, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fReasonSettingrows != null) {
						if (fReasonSettingrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fReasonSettingrows 13");
						} else {
							Log.v(TAG, "fReason 13:" + ReaCode.trim());
							newrowfReason.put("AddDate", AddDate.trim());
							newrowfReason.put("AddMach", AddMach.trim());
							newrowfReason.put("AddUser", AddUser.trim());
							newrowfReason.put("ReaCode", ReaCode.trim());
							newrowfReason.put("ReaName", ReaName.trim());
							newrowfReason.put("ReaTcode", ReaTcode.trim());
							newrowfReason.put("RecordId ", RecordId.trim());
							newrowfReason.put("Type", Type.trim());
							mydb.insert(SALES_ORD_REASON, null, newrowfReason);
							fReasonSettingrows.close();
						}
					}
					mydb.close();

				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 13: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfReason.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fRoute**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fRoute/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfRoute = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfRoute.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfRoute = jsonResponse
						.getJSONArray("fRouteResult");
				Log.v(TAG, "Array Length fRoute :" + jsonArrayfRoute.length());
				for (int i = 0; i < jsonArrayfRoute.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfRoute.get(i);
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String RouteName = jObject.getString("RouteName");
					String RecordId = jObject.getString("RecordId");
					String AddDate = jObject.getString("AddDate");
					String AreaCode = jObject.getString("AreaCode");
					String DealCode = jObject.getString("DealCode");
					String FreqNo = jObject.getString("FreqNo");
					String Km = jObject.getString("Km");
					String MinProcall = jObject.getString("MinProcall");
					String RDAloRate = jObject.getString("RDAloRate");
					String RDTarget = jObject.getString("RDTarget");
					String Remarks = jObject.getString("Remarks");
					String Status = jObject.getString("Status");
					String Tonnage = jObject.getString("Tonnage");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfRoute = new ContentValues();
					Cursor frouterows = null;
					try {
						frouterows = mydb.query(SALES_REP_ROUTE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (frouterows != null) {
						if (frouterows.getCount() >= 1) {
							Log.v(TAG, "Excisting frouterows 14");
						} else {
							Log.v(TAG, "fRoute 14:" + RouteCode.trim());
							newrowfRoute.put("RepCode", RepCode.trim());
							newrowfRoute.put("RouteCode", RouteCode.trim());
							newrowfRoute.put("RouteName", RouteName.trim());
							newrowfRoute.put("RecordId", RecordId.trim());
							newrowfRoute.put("AddDate", AddDate.trim());
							newrowfRoute.put("AreaCode", AreaCode.trim());
							newrowfRoute.put("DealCode", DealCode.trim());
							newrowfRoute.put("FreqNo", FreqNo.trim());
							newrowfRoute.put("Km", Km.trim());
							newrowfRoute.put("MinProcall", MinProcall.trim());
							newrowfRoute.put("RDAloRate", RDAloRate.trim());
							newrowfRoute.put("RDTarget", RDTarget.trim());
							newrowfRoute.put("Remarks", Remarks.trim());
							newrowfRoute.put("Status", Status.trim());
							newrowfRoute.put("Tonnage", Tonnage.trim());
							mydb.insert(SALES_REP_ROUTE, null, newrowfRoute);
							frouterows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 14: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfRoute.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fbank**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fbank/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfbank = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfbank.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfbank = jsonResponse
						.getJSONArray("fbankResult");
				Log.v(TAG, "Array Length fbank :" + jsonArrayfbank.length());
				for (int i = 0; i < jsonArrayfbank.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfbank.get(i);
					String RecordId = jObject.getString("RecordId");
					String bankcode = jObject.getString("bankcode");
					String bankname = jObject.getString("bankname");
					String bankaccno = jObject.getString("bankaccno");
					String Branch = jObject.getString("Branch");
					String bankadd1 = jObject.getString("bankadd1");
					String bankadd2 = jObject.getString("bankadd2");
					String AddDate = jObject.getString("AddDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfbank = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(BANK_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 15");
						} else {
							Log.v(TAG, "fbank 15:" + bankcode.trim());
							newrowfbank.put("RecordId", RecordId.trim());
							newrowfbank.put("bankcode", bankcode.trim());
							newrowfbank.put("bankname", bankname.trim());
							newrowfbank.put("bankaccno", bankaccno.trim());
							newrowfbank.put("Branch", Branch.trim());
							newrowfbank.put("bankadd1", bankadd1.trim());
							newrowfbank.put("bankadd2", bankadd2.trim());
							newrowfbank.put("AddDate", AddDate.trim());
							mydb.insert(BANK_DETAILS, null, newrowfbank);
							adminuserrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 15: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfbank.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ***************Download fDdbNote*********************************
			// TODO Auto-generated method stub
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fDdbNote/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfDdbNote = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfDdbNote.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfDdbNote = jsonResponse
						.getJSONArray("fDdbNoteResult");
				Log.v(TAG,
						"Array Length fDdbNote :" + jsonArrayfDdbNote.length());
				for (int i = 0; i < jsonArrayfDdbNote.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfDdbNote.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String CrAcc = jObject.getString("CrAcc");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DebCode = jObject.getString("DebCode");
					String GlPost = jObject.getString("GlPost");
					String ManuRef = jObject.getString("ManuRef");
					String OvPayAmt = jObject.getString("OvPayAmt");
					String PrtCopy = jObject.getString("PrtCopy");
					String RecordId = jObject.getString("RecordId");
					String RefInv = jObject.getString("RefInv");
					String RefNo = jObject.getString("RefNo");
					String RefNo1 = jObject.getString("RefNo1");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String SaleRefNo = jObject.getString("SaleRefNo");
					String TaxAmt = jObject.getString("TaxAmt");
					String TaxComCode = jObject.getString("TaxComCode");
					String TotBal = jObject.getString("TotBal");
					String TotBal1 = jObject.getString("TotBal1");
					String TxnDate = jObject.getString("TxnDate");
					String TxnType = jObject.getString("TxnType");
					String glbatch = jObject.getString("glbatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfDdbNote = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(RECEIPT_INVOICES, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 16");
						} else {
							Log.v(TAG, "fDdbNote 16:" + RecordId.trim());
							newrowfDdbNote.put("RecordId", RecordId.trim());
							newrowfDdbNote.put("RefNo", RefNo.trim());
							newrowfDdbNote.put("RefInv", RefInv.trim());
							newrowfDdbNote.put("SaleRefNo", SaleRefNo.trim());
							newrowfDdbNote.put("ManuRef", ManuRef.trim());
							newrowfDdbNote.put("TxnType", TxnType.trim());
							newrowfDdbNote.put("TxnDate", TxnDate.trim());
							newrowfDdbNote.put("CurCode", CurCode.trim());
							newrowfDdbNote.put("CurRate", CurRate.trim());
							newrowfDdbNote.put("DebCode", DebCode.trim());
							newrowfDdbNote.put("RepCode", RepCode.trim());
							newrowfDdbNote.put("TaxComCode", TaxComCode.trim());
							newrowfDdbNote.put("TaxAmt", TaxAmt.trim());
							newrowfDdbNote.put("BTaxAmt", BTaxAmt.trim());
							newrowfDdbNote.put("Amt", Amt.trim());
							newrowfDdbNote.put("BAmt", BAmt.trim());
							newrowfDdbNote.put("TotBal", TotBal.trim());
							newrowfDdbNote.put("TotBal1", TotBal1.trim());
							newrowfDdbNote.put("OvPayAmt", OvPayAmt.trim());
							newrowfDdbNote.put("Remarks", Remarks.trim());
							newrowfDdbNote.put("CrAcc", CrAcc.trim());
							newrowfDdbNote.put("PrtCopy", PrtCopy.trim());
							newrowfDdbNote.put("GlPost", GlPost.trim());
							newrowfDdbNote.put("glbatch", glbatch.trim());
							newrowfDdbNote.put("AddUser", AddUser.trim());
							newrowfDdbNote.put("AddDate", AddDate.trim());
							newrowfDdbNote.put("AddMach", AddMach.trim());
							newrowfDdbNote.put("RefNo1", RefNo1.trim());
							mydb.insert(RECEIPT_INVOICES, null, newrowfDdbNote);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 16: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfDdbNote.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fExpense**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fExpense/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfexpense = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfexpense.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfExpense = jsonResponse
						.getJSONArray("fExpenseResult");
				Log.v(TAG,
						"Array Length fDdbNote :" + jsonArrayfExpense.length());
				for (int i = 0; i < jsonArrayfExpense.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfExpense.get(i);
					String ExpCode = jObject.getString("ExpCode");
					String ExpGrpCode = jObject.getString("ExpGrpCode");
					String ExpName = jObject.getString("ExpName");
					String RecordId = jObject.getString("RecordId");
					String Status = jObject.getString("Status");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfexpense = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(USER_EXPENSE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 17");
						} else {
							Log.v(TAG, "fExpense 17:" + ExpCode.trim());
							newrowfexpense.put("ExpCode", ExpCode.trim());
							newrowfexpense.put("ExpGrpCode", ExpGrpCode.trim());
							newrowfexpense.put("ExpName", ExpName.trim());
							newrowfexpense.put("RecordId", RecordId.trim());
							newrowfexpense.put("Status", Status.trim());
							newrowfexpense.put("AddMach", AddMach.trim());
							newrowfexpense.put("AddUser", AddUser.trim());
							mydb.insert(USER_EXPENSE, null, newrowfexpense);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 17: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfexpense.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fTown**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fTown/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfTown = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfTown.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfTown = jsonResponse
						.getJSONArray("fTownResult");
				Log.v(TAG, "Array Length fTown :" + jsonArrayfTown.length());
				for (int i = 0; i < jsonArrayfTown.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfTown.get(i);
					String RecordId = jObject.getString("RecordId");
					String TownCode = jObject.getString("TownCode");
					String TownName = jObject.getString("TownName");
					String DistrCode = jObject.getString("DistrCode");
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfTown = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(TOWN_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 18");
						} else {
							Log.v(TAG, "fTown 18:" + TownCode.trim());
							newrowfTown.put("RecordId", RecordId.trim());
							newrowfTown.put("TownCode", TownCode.trim());
							newrowfTown.put("TownName", TownName.trim());
							newrowfTown.put("DistrCode", DistrCode.trim());
							newrowfTown.put("AddDate", AddDate.trim());
							newrowfTown.put("AddMach", AddMach.trim());
							newrowfTown.put("AddUser", AddUser.trim());
							mydb.insert(TOWN_DETAILS, null, newrowfTown);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 18: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfTown.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download FMerch**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FMerch/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFMerch = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFMerch.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFMerch = jsonResponse
						.getJSONArray("FMerchResult");
				Log.v(TAG, "Array Length FMerch :" + jsonArrayFMerch.length());
				for (int i = 0; i < jsonArrayFMerch.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFMerch.get(i);
					String RecordId = jObject.getString("RecordId");
					String MerchCode = jObject.getString("MerchCode");
					String MerchName = jObject.getString("MerchName");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String AddDate = jObject.getString("AddDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowFMerch = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(MERCH_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 19");
						} else {
							Log.v(TAG, "FMerch 19:" + MerchCode.trim());
							newrowFMerch.put("RecordId", RecordId.trim());
							newrowFMerch.put("MerchCode", MerchCode.trim());
							newrowFMerch.put("MerchName", MerchName.trim());
							newrowFMerch.put("AddUser", AddUser.trim());
							newrowFMerch.put("AddMach", AddMach.trim());
							newrowFMerch.put("AddDate", AddDate.trim());

							mydb.insert(MERCH_DETAILS, null, newrowFMerch);
							adminuserrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 19: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFMerch.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fRouteDet details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fRouteDet/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfdblist.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfRouteDet = jsonResponse
						.getJSONArray("fRouteDetResult");
				Log.v(TAG,
						"Array Length fRouteDet :"
								+ jsonArrayfRouteDet.length());
				for (int i = 0; i < jsonArrayfRouteDet.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfRouteDet.get(i);
					String RecordId = jObject.getString("RecordId");
					String DebCode = jObject.getString("DebCode");
					String RouteCode = jObject.getString("RouteCode");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowrepdetlist = new ContentValues();
					Cursor routedetlistrows = null;
					try {
						routedetlistrows = mydb.query(SALES_REP_ROUTEDET, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (routedetlistrows != null) {
						if (routedetlistrows.getCount() >= 1) {
							Log.v(TAG, "Excisting routedetlistrows 20");
						} else {
							Log.v(TAG, "fRouteDet 20:" + RecordId.trim());
							newrowrepdetlist.put("RecordId", RecordId.trim());
							newrowrepdetlist.put("DebCode", DebCode.trim());
							newrowrepdetlist.put("RouteCode", RouteCode.trim());
							mydb.insert(SALES_REP_ROUTEDET, null,
									newrowrepdetlist);
							routedetlistrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 20: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfdblist.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// ******Download Available FTrgCapUL details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FTrgCapUL/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFTrgCapUL = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFTrgCapUL.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFTrgCapUL = jsonResponse
						.getJSONArray("FTrgCapULResult");
				Log.v(TAG,
						"Array Length FTrgCapUL :"
								+ jsonArrayFTrgCapUL.length());
				for (int i = 0; i < jsonArrayFTrgCapUL.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFTrgCapUL.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String DealCode = jObject.getString("DealCode");
					String Month = jObject.getString("Month");
					String Qty = jObject.getString("Qty");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String SKUCode = jObject.getString("SKUCode");
					String Year = jObject.getString("Year");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowftrgcapul = new ContentValues();
					Cursor ftrgcapulrows = null;
					try {
						ftrgcapulrows = mydb.query(FTRGCAPUL, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (ftrgcapulrows != null) {
						if (ftrgcapulrows.getCount() >= 1) {
							Log.v(TAG, "Excisting ftrgcapulrows 21");
						} else
							Log.v(TAG, "FTrgCapUL 21:" + RecordId.trim());
						newrowftrgcapul.put("AddDate", AddDate.trim());
						newrowftrgcapul.put("AddMach", AddMach.trim());
						newrowftrgcapul.put("AddMach", AddMach.trim());
						newrowftrgcapul.put("AddUser", AddUser.trim());
						newrowftrgcapul.put("DealCode", DealCode.trim());
						newrowftrgcapul.put("Month", Month.trim());
						newrowftrgcapul.put("Qty", Qty.trim());
						newrowftrgcapul.put("RecordId", RecordId.trim());
						newrowftrgcapul.put("RepCode", RepCode.trim());
						newrowftrgcapul.put("SKUCode", SKUCode.trim());
						newrowftrgcapul.put("Year", Year.trim());
						mydb.insert(FTRGCAPUL, null, newrowftrgcapul);
						ftrgcapulrows.close();

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 21: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFTrgCapUL.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fType details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fType/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfType = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfType.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfType = jsonResponse
						.getJSONArray("fTypeResult");
				Log.v(TAG, "Array Length fType :" + jsonArrayfType.length());
				for (int i = 0; i < jsonArrayfType.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfType.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String RecordId = jObject.getString("RecordId");
					String TypeCode = jObject.getString("TypeCode");
					String TypeName = jObject.getString("TypeName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowftype = new ContentValues();
					Cursor ftyperows = null;
					try {
						ftyperows = mydb
								.query(FTYPE, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (ftyperows != null) {
						if (ftyperows.getCount() >= 1) {
							Log.v(TAG, "Excisting ftyperows 22");
						} else {
							Log.v(TAG, "fType 22:" + RecordId.trim());
							newrowftype.put("AddDate", AddDate.trim());
							newrowftype.put("AddMach", AddMach.trim());
							newrowftype.put("AddUser", AddUser.trim());
							newrowftype.put("RecordId", RecordId.trim());
							newrowftype.put("TypeCode", TypeCode.trim());
							newrowftype.put("TypeName", TypeName.trim());
							mydb.insert(FTYPE, null, newrowftype);
							ftyperows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 22: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfType.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fSubBrand details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fSubBrand/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfSubBrand = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfSubBrand.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfSubBrand = jsonResponse
						.getJSONArray("fSubBrandResult");
				Log.v(TAG,
						"Array Length fSubBrand :"
								+ jsonArrayfSubBrand.length());
				for (int i = 0; i < jsonArrayfSubBrand.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfSubBrand.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String RecordId = jObject.getString("RecordId");
					String SBrandCode = jObject.getString("SBrandCode");
					String SBrandName = jObject.getString("SBrandName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfSubBrand = new ContentValues();
					Cursor fSubBrandrows = null;
					try {
						fSubBrandrows = mydb.query(FSUBBRAND, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fSubBrandrows != null) {
						if (fSubBrandrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fSubBrandrows 23");
						} else
							Log.v(TAG, "fSubBrand: 23" + RecordId.trim());
						newrowfSubBrand.put("AddDate", AddDate.trim());
						newrowfSubBrand.put("AddMach", AddMach.trim());
						newrowfSubBrand.put("AddUser", AddUser.trim());
						newrowfSubBrand.put("RecordId", RecordId.trim());
						newrowfSubBrand.put("SBrandCode", SBrandCode.trim());
						newrowfSubBrand.put("SBrandName", SBrandName.trim());
						mydb.insert(FSUBBRAND, null, newrowfSubBrand);
						fSubBrandrows.close();
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 23: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfSubBrand.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fGroup details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fGroup/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfGroup = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfGroup.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfGroup = jsonResponse
						.getJSONArray("fGroupResult");
				Log.v(TAG, "Array Length fGroup :" + jsonArrayfGroup.length());
				for (int i = 0; i < jsonArrayfGroup.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfGroup.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String GroupCode = jObject.getString("GroupCode");
					String GroupName = jObject.getString("GroupName");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfGroup = new ContentValues();
					Cursor fGrouprows = null;
					try {
						fGrouprows = mydb
								.query(FGROUP, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fGrouprows != null) {
						if (fGrouprows.getCount() >= 1) {
							Log.v(TAG, "Excisting fGrouprows 24");
						} else {
							Log.v(TAG, "fGroup 24:" + RecordId.trim());
							newrowfGroup.put("AddDate", AddDate.trim());
							newrowfGroup.put("AddMach", AddMach.trim());
							newrowfGroup.put("AddUser", AddUser.trim());
							newrowfGroup.put("GroupCode", GroupCode.trim());
							newrowfGroup.put("GroupName", GroupName.trim());
							newrowfGroup.put("RecordId", RecordId.trim());
							mydb.insert(FGROUP, null, newrowfGroup);
							fGrouprows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 24: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfGroup.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available FSKU details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FSKU/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfsku = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfsku.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFSKU = jsonResponse
						.getJSONArray("FSKUResult");
				Log.v(TAG, "Array Length FSKU :" + jsonArrayFSKU.length());
				for (int i = 0; i < jsonArrayFSKU.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFSKU.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String BrandCode = jObject.getString("BrandCode");
					String GroupCode = jObject.getString("GroupCode");
					String ItemStatus = jObject.getString("ItemStatus");
					String MustSale = jObject.getString("MustSale");
					String NOUCase = jObject.getString("NOUCase");
					String OrdSeq = jObject.getString("OrdSeq");
					String RecordId = jObject.getString("RecordId");
					String SBrandCode = jObject.getString("SBrandCode");
					String SKUCode = jObject.getString("SKUCode");
					String SkuName = jObject.getString("SkuName");
					String SkuSizCode = jObject.getString("SkuSizCode");
					String Tonnage = jObject.getString("Tonnage");
					String TypeCode = jObject.getString("TypeCode");
					String Unit = jObject.getString("Unit");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfsku = new ContentValues();
					Cursor fskurows = null;
					try {
						fskurows = mydb
								.query(FSKU, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fskurows != null) {
						if (fskurows.getCount() >= 1) {
							Log.v(TAG, "Excisting fskurows 25");
						} else {
							Log.v(TAG, "FSKU 25:" + RecordId.trim());
							newrowfsku.put("AddDate", AddDate.trim());
							newrowfsku.put("AddMach", AddMach.trim());
							newrowfsku.put("AddUser", AddUser.trim());
							newrowfsku.put("BrandCode", BrandCode.trim());
							newrowfsku.put("GroupCode", GroupCode.trim());
							newrowfsku.put("ItemStatus", ItemStatus.trim());
							newrowfsku.put("MustSale", MustSale.trim());
							newrowfsku.put("NOUCase", NOUCase.trim());
							newrowfsku.put("OrdSeq", OrdSeq.trim());
							newrowfsku.put("RecordId", RecordId.trim());
							newrowfsku.put("SBrandCode", SBrandCode.trim());
							newrowfsku.put("SKUCode", SKUCode.trim());
							newrowfsku.put("SkuName", SkuName.trim());
							newrowfsku.put("SkuSizCode", SkuSizCode.trim());
							newrowfsku.put("Tonnage", Tonnage.trim());
							newrowfsku.put("TypeCode", TypeCode.trim());
							try {
								if (Unit.length() == 0) {
									Unit = "0";
								} else {
									Unit = Unit.trim();
								}
							} catch (Exception e) {
								Unit = "0";
							}
							newrowfsku.put("Unit", Unit);
							mydb.insert(FSKU, null, newrowfsku);
							fskurows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 25: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfsku.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fbrand details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fbrand/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfbrand = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfbrand.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFbrand = jsonResponse
						.getJSONArray("FbrandResult");
				Log.v(TAG, "Array Length Fbrand :" + jsonArrayFbrand.length());
				for (int i = 0; i < jsonArrayFbrand.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFbrand.get(i);
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String BrandCode = jObject.getString("BrandCode");
					String BrandName = jObject.getString("BrandName");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfbrand = new ContentValues();
					Cursor fbrandrows = null;
					try {
						fbrandrows = mydb
								.query(FBRAND, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fbrandrows != null) {
						if (fbrandrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fbrandrows 26");
						} else {
							Log.v(TAG, "fbrand 26:" + RecordId.trim());
							newrowfbrand.put("AddMach", AddMach.trim());
							newrowfbrand.put("AddUser", AddUser.trim());
							newrowfbrand.put("BrandCode", BrandCode.trim());
							newrowfbrand.put("BrandName", BrandName.trim());
							newrowfbrand.put("RecordId", RecordId.trim());
							mydb.insert(FBRAND, null, newrowfbrand);
							fbrandrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 26: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfbrand.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// ******Download Available fDealer details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fDealer/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfDealer = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfDealer.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fDealerResult");

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String DealCode = jObject.getString("DealCode");
					String DealName = jObject.getString("DealName");
					String DealAdd1 = jObject.getString("DealAdd1");
					String DealAdd2 = jObject.getString("DealAdd2");
					String DealAdd3 = jObject.getString("DealAdd3");
					String DealTele = jObject.getString("DealTele");
					String DealMob = jObject.getString("DealMob");
					String DealEMail = jObject.getString("DealEMail");
					String Status = jObject.getString("Status");
					String Distance = jObject.getString("Distance");
					String DealGdCode = jObject.getString("DealGdCode");
					String CusTypCode = jObject.getString("CusTypCode");
					String AddUser = jObject.getString("AddUser");
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfDealer = new ContentValues();
					Cursor fdealerrows = null;
					try {
						fdealerrows = mydb.query(SALES_DEALER, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fdealerrows != null) {
						if (fdealerrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fdealerrows 24");
						} else {
							Log.v(TAG, "fDealer 25:" + RecordId.trim());
							newrowfDealer.put("DealCode", DealCode.trim());
							newrowfDealer.put("DealName", DealName.trim());
							newrowfDealer.put("DealAdd1", DealAdd1.trim());
							newrowfDealer.put("DealAdd2", DealAdd2.trim());
							newrowfDealer.put("DealAdd3", DealAdd3.trim());
							newrowfDealer.put("DealTele", DealTele.trim());
							newrowfDealer.put("DealMob", DealMob.trim());
							newrowfDealer.put("DealEMail", DealEMail.trim());
							newrowfDealer.put("Status", Status.trim());
							newrowfDealer.put("Distance", Distance.trim());
							newrowfDealer.put("DealGdCode", DealGdCode.trim());
							newrowfDealer.put("CusTypCode", CusTypCode.trim());
							newrowfDealer.put("AddUser", AddUser.trim());
							newrowfDealer.put("AddDate", AddDate.trim());
							newrowfDealer.put("AddMach", AddMach.trim());
							newrowfDealer.put("RecordId", RecordId.trim());
							mydb.insert(SALES_DEALER, null, newrowfDealer);
							fdealerrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfDealer.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			mydb.close();
			arrayLength = 3;
			progressHandler.sendMessage(progressHandler.obtainMessage());
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (NetFail == 0) {
				mProgressDialog.dismiss();
				// arrayLength = 100;
				try {
					showDialog(DIALOG_SYNC_SUCCESS);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (NetFail == 404) {
				countDownActivator();
			}

		}

	}

	// handler for the background updating
	Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.v(TAG, "Array Length XXX :" + arrayLength);
			mProgressDialog.incrementProgressBy(arrayLength);
		}
	};

	protected void UpdateUserSettings() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUdateUserPrinterSetting = null;
		try {
			curUdateUserPrinterSetting = mydb.query(USER_SETTINGS, null,
					"username = '" + CurrentUser + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUdateUserPrinterSetting != null) {
			if (curUdateUserPrinterSetting.getCount() > 0) {
				while (curUdateUserPrinterSetting.moveToNext()) {

					String CurrentUserId = curUdateUserPrinterSetting
							.getString(0);
					CurrentUser = curUdateUserPrinterSetting.getString(1);
					ContentValues userPrinter = new ContentValues();
					userPrinter.put("username", etsettingsrepcode.getText()
							.toString());
					userPrinter.put("lrepprefix", etsettingsrepprefix.getText()
							.toString());
					userPrinter.put("lreploccode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("locationCode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("serverDbName", etsettingssdb.getText()
							.toString());
					userPrinter.put("printerMac", etsettingsprintermac
							.getText().toString());
					userPrinter.put("repareacode", etsettingsareacode.getText()
							.toString());
					userPrinter.put("repdealcode", etsettingsdealcode.getText()
							.toString());
					userPrinter.put("reproutecode", etsettingsroutecode
							.getText().toString());
					mydb.update(USER_SETTINGS, userPrinter, "username ='"
							+ CurrentUser + "'", null);

				}
			}
		} else {
			try {
				ContentValues user = new ContentValues();
				user.put("username", "admin");
				user.put("lrepprefix", "");
				user.put("lreploccode", "");
				user.put("currentStOrdNo", "");
				user.put("locationCode", "");
				user.put("receiptCode", "");
				user.put("serverDbName", serverDbName);
				user.put("printerMac", "00:22:58:3A:C6:49");
				user.put("repareacode", "");
				user.put("repdealcode", "");
				user.put("reproutecode", "");
				mydb.insert(USER_SETTINGS, null, user);
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(),
				// Toast.LENGTH_LONG).show();
			}

		}
	}

	private void displayCurrentSettings() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		String userSettingsQuery;
		try {
			
			userSettingsQuery = "SELECT s.username,s.lrepprefix,s.lreploccode,s.locationCode,s.receiptCode,s.serverDbName,s.printerMac,s.repareacode,s.repdealcode,s.reproutecode,r.RepName,r.RepCode From fSalRep r,usersettings s Where r.RepCode = s.username";
			curUserSettings = mydb.rawQuery(userSettingsQuery, null);
			/*curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);*/
		} catch (Exception e) {
		}
		//Log.v(TAG, "User Count:" + curUserSettings.getCount());
		if (curUserSettings != null) {
			if (curUserSettings.getCount() >= 1) {
				while (curUserSettings.moveToNext()) {
					
					CurrentUser = curUserSettings.getString(0);
					String lrepprefix = curUserSettings.getString(1);
					String lreploccode = curUserSettings.getString(2);
					String locationCode = curUserSettings.getString(3);
					String receiptCode = curUserSettings.getString(4);
					String serverDbName = curUserSettings.getString(5);
					String printerMac = curUserSettings.getString(6);
					String repareacode = curUserSettings.getString(7);
					String repdealcode = curUserSettings.getString(8);
					String reproutecode = curUserSettings.getString(9);
					String RepName = curUserSettings.getString(10);
					String RepCode = curUserSettings.getString(11);

					etsettingssdb.setText(serverDbName);
					etsettingsrepprefix.setText(lrepprefix);
					etsettingsprintermac.setText(printerMac);
					etsettingsuser.setText(RepName);
					etsettingsrepcode.setText(CurrentUser);
					etsettingslocationcode.setText(lreploccode);
					etsettingsareacode.setText(repareacode);
					etsettingsdealcode.setText(repdealcode);
					etsettingsroutecode.setText(reproutecode);
				}
			}
		}
	}

	public void checkNetwork() {
		// TODO Auto-generated method stub
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			Log.v(TAG, "Net Work Present........");
			NetFail = 0;
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			// showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
			// "You don't have internet connection.", false);
			Log.v(TAG, "Net Work Disabled........");
			NetFail = 404;
			countDownActivator();
		}
	}

	private void countDownActivator() {
		// TODO Auto-generated method stub
		mCountDown = new CountDownTimer(30000, 1000) {

			@Override
			public void onFinish() {
				mProgressDialog.dismiss();
				showAlertDialog(
						DM_Settings.this,
						"Internet Connection Lost..",
						"Your Internet Connection Lost During Syncing.Data Sync Not Completed. Tap OK to Continue Sync..",
						false);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v(TAG, "Time Remaining Chk 1:" + millisUntilFinished / 1000);
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					NetFail = 0;
					arrayLength = 0;
					// Internet Connection is Present
					// Stop coun down
					mCountDown.cancel();
				} else {
					// Internet connection is not present

				}
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	@SuppressLint("SimpleDateFormat")
	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	// Handling Dialog Box Functions

	// XML Builder

	class XmlBuilder {
		private static final String OPEN_XML_STANZA = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		private static final String CLOSE_WITH_TICK = "'>";
		private static final String DB_OPEN = "<database name='";
		private static final String DB_CLOSE = "</database>";
		private static final String TABLE_OPEN = "<table name='";
		private static final String TABLE_CLOSE = "</table>";
		private static final String ROW_OPEN = "<row>";
		private static final String ROW_CLOSE = "</row>";
		private static final String COL_OPEN = "<col name='";
		private static final String COL_CLOSE = "</col>";

		private final StringBuilder sb;

		public XmlBuilder() throws IOException {
			this.sb = new StringBuilder();
		}

		void start(String dbName) {
			this.sb.append(OPEN_XML_STANZA);
			this.sb.append(DB_OPEN + dbName + CLOSE_WITH_TICK);
		}

		String end() throws IOException {
			this.sb.append(DB_CLOSE);
			return this.sb.toString();
		}

		void openTable(String tableName) {
			this.sb.append(TABLE_OPEN + tableName + CLOSE_WITH_TICK);
		}

		void closeTable() {
			this.sb.append(TABLE_CLOSE);
		}

		void openRow() {
			this.sb.append(ROW_OPEN);
		}

		void closeRow() {
			this.sb.append(ROW_CLOSE);
		}

		void addColumn(final String name, final String val) throws IOException {
			this.sb.append(COL_OPEN + name + CLOSE_WITH_TICK + val + COL_CLOSE);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {

		case DATE_DIALOG_ID_FROM:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case DATE_DIALOG_ID_TO:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListenerTo, mYear,
					mMonth, mDay);
		case DIALOG_SYNC_SUCCESS:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(R.layout.dm_dialog_sync_success,
					null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Sync Data Completed. Select SalesRef...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
		}
		return InvoiceHeaderAlert;
	}

	// Register DatePickerDialog listener
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// the callback received when the user "sets" the Date in the
		// DatePickerDialog
		public void onDateSet(DatePicker view, int yearSelected,
				int monthOfYear, int dayOfMonth) {
			mYear = yearSelected;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			String mMonthStr = Integer.toString(mMonth);
			String mDayStr = Integer.toString(mDay);
			if (mMonthStr.length() == 1) {
				mMonthStr = "0" + mMonthStr;
			}
			if (mDayStr.length() == 1) {
				mDayStr = "0" + mDayStr;
			}
			btndmreportfromdate
					.setText(mDayStr + "/" + mMonthStr + "/" + mYear);
			mMonth = mMonth - 1;
		}
	};
	// Register DatePickerDialog listener
	private DatePickerDialog.OnDateSetListener mDateSetListenerTo = new DatePickerDialog.OnDateSetListener() {
		// the callback received when the user "sets" the Date in the
		// DatePickerDialog
		public void onDateSet(DatePicker view, int yearSelected,
				int monthOfYear, int dayOfMonth) {
			mYear = yearSelected;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			String mMonthStr = Integer.toString(mMonth);
			String mDayStr = Integer.toString(mDay);
			if (mMonthStr.length() == 1) {
				mMonthStr = "0" + mMonthStr;
			}
			if (mDayStr.length() == 1) {
				mDayStr = "0" + mDayStr;
			}
			btndmreporttodate.setText(mDayStr + "/" + mMonthStr + "/" + mYear);
			mMonth = mMonth - 1;
		}
	};

	public static boolean isExternalStorageReadOnly() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	public static boolean isExternalStorageAvailable() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
			return true;
		}
		return false;
	}
}
